package com.yimi.yinhepda.views.load_module;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.db.table.UnloadScanTable;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.entity.bean.LoadBillTaskEntity;
import com.pda.ym.entity.bean.VehTaskNodeEntity;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.FastClick;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.pda.ym.utils.SysInfo;
import com.uce.pda.bean.SonScanStatictisBan;
import com.uce.pda.module.ConnectionResultLister;
import com.uce.pda.module.OneToMoreModule;
import com.uce.pda.util.ArrayUtils;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.LoadScanAdapter;
import com.yimi.yinhepda.callbacks.OnClickCallBack;
import com.yimi.yinhepda.db.dao.BillRouteTableDao;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.JieLiuJianTableDao;
import com.yimi.yinhepda.db.dao.LoadUnloadGroupTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.BillRouteTable;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LoadUnLoadGroupTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.BaseDictEntity;
import com.yimi.yinhepda.entity.bean.CarModelLimitWeightEntity;
import com.yimi.yinhepda.entity.bean.CheckBoxItemEntity;
import com.yimi.yinhepda.entity.bean.JoinPeopleEntity;
import com.yimi.yinhepda.entity.request.FinishTaskUploadRequest;
import com.yimi.yinhepda.entity.request.QueryLoadDetailRequest;
import com.yimi.yinhepda.entity.request.QueryWaybillByChildNoRequest;
import com.yimi.yinhepda.entity.request.ScanLoadUploadRequest;
import com.yimi.yinhepda.entity.response.LoadInfo;
import com.yimi.yinhepda.entity.response.QueryBaseDictResponse;
import com.yimi.yinhepda.entity.response.QueryLoadDetailBillcode;
import com.yimi.yinhepda.entity.response.QueryLoadDetailChildBillcode;
import com.yimi.yinhepda.entity.response.QueryLoadDetailResponse;
import com.yimi.yinhepda.entity.response.QueryUnloadDetailResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.yimi.yinhepda.event.CreateStowagesEvent;
import com.yimi.yinhepda.event.ScanResult;
import com.yimi.yinhepda.utils.BigDecimalUtils;
import com.yimi.yinhepda.utils.CheckNetTimeUtil;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.DialogUtil;
import com.yimi.yinhepda.utils.HiddenAnimUtils;
import com.yimi.yinhepda.utils.ListUtils;
import com.yimi.yinhepda.utils.ThreadPoolUtils;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.utils.UcWaybillValidate;
import com.yimi.yinhepda.views.load_module.module.CheckMergeLoadModule;
import com.yimi.yinhepda.views.unload_module.AddBillcodeActivity;
import com.yimi.yinhepda.views.unload_module.UnloadCompareActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 装车扫描界面
 *
 * @author 000432
 */
public class LoadScanActivity extends LoadBaseActivity implements View.OnTouchListener, CompoundButton.OnCheckedChangeListener {
    protected ListView listview;
    private ScrollView mScrollView;
    private LoadScanAdapter adapter;

    /**
     * 配载单号
     */
    private String carCode;
    private String carNo;
    private String currentStation, currentStationCode, nextStation, nextStationCode, task;
    private TextView totle_weight, totle_volume, totle_piao, totle_jian, hold_weight, hold_volume, hold_piao, hold_jian, next_station;
    /**
     * 输入方式 1-PDA扫描输入,2-手动输入
     */
    private int inputType = 1;
    private boolean isfirst = true;
    /**
     * 是否退出上传线程
     */
    private boolean isExit = false;
    /**
     * 计费总量
     */
    private double sfweight = 0.0;
    /**
     * 实际扫描重量
     */
    private double mRealWeight = 0.0;
    public static final int LOADSCAN_RESULT = 101;
    public static final int BACK_OUT_RESULT = 102;
    public static List<LoadInfo> loadInfos;
    private MyDialog dialog;
    /**
     * 是否点击刷新按钮
     */
    private boolean isClickFlash = false;
    /**
     * 是否点击提交
     */
    private boolean isClickSubmit = false;
    /**
     * 发车计划任务集合
     */
    public static List<CarPlanTaskEntity> carPlanTaskEntityList;
    private List<JoinPeopleEntity> mJoinPeopleEntityList;
    /**
     * 刷新按钮
     */
    private Button flashBtn;
    /**
     * 手动添加按钮
     */
    private Button btnAdd;
    /**
     * 刷新计时标志
     */
    private int flashCount = 0;
    private boolean isClickLoadData = false;
    /**
     * 参与人工号
     */
    private String joinWrokNum;
    /**
     * 参与人姓名
     */
    private String joinUserName;
    /**
     * 部门类型
     */
    private Integer deptType;
    /**
     * 扫描描述
     */
    private TextView tvShowDesc;
    /**
     * 装卸组按钮
     */
    private Button btnLoadUnloadGroup;
    /**
     * 月台号
     */
    private String platformNo;
    /**
     * 向下按钮
     */
    private ImageView ivDownLayout;
    /**
     * 要隐藏显示的布局
     */
    private LinearLayout llFunctionBtn;
    /**
     * 装车发车时间
     */
    private TextView tvloadTime;
    /**
     * 卸车任务倒计时
     */
    private Timer mTimer;
    //额定载重
    private double mLoadLimit;
    //装载率文本控件
    private TextView tvLoadLimit;
    /**
     * 卡航总重量
     */
    private TextView tvKaTotalWeight;
    /**
     * 卡航总体积
     */
    private TextView tvKaTotalVolume;
    /**
     * 卡航总体积
     */
    private TextView tvKaShiWeight;
    /**
     * 卡航总体积
     */
    private TextView tvKaShiVolume;
    /**
     * 快运快递复选框
     */
    private CheckBox cbKuaiYun, cbKuaiDi;
    private long mMinutes = 0;
    private int timeSS = 60;
    private boolean isTimeScan = false;
    private final int HANDLER_100 = 100;
    private Handler handler;
    private boolean isFirstScan = true;
    private boolean isUcOneTask;
    private boolean isYmOneTask;
    private boolean isKuaYueTask;
    /**
     * 快运、快递默认的第一个装车任务
     */
    private LoadBillTaskEntity mYmLoadTask, mUcLoadTask;
    /**
     * 车型校验开关数据字典
     */
    private List<BaseDictEntity> mDictSwitchList;
    /**
     * 车型数据字典
     */
    private List<BaseDictEntity> mDictCarModelList;
    /**
     * 运单改单重量差值 数据字典
     */
    private List<BaseDictEntity> mDictWeightChangeDiffList;
    /**
     * 运单重量差值
     */
    private double mWeightDiff;
    /**
     * 限重的配载单
     */
    private List<CarModelLimitWeightEntity> mLimitWeightStowage;
    /**
     * 快递错分开关标志
     */
    private boolean isUcCuoFenSwitch;
    private final String FINAL_UNLOAD_SCAN_TABLE = "finalUnloadSanTable";
    private final String FINAL_LOAD_INFO = "finalLoadInfo";
    private DepartmentTableDao mDepartmentTableDao;

    /**
     * 壹米和快递运单是否已经扫描
     */
    private boolean mYmScaned, mUcScaned;
    private JieLiuJianTableDao mJieLiuJianTableDao;
    private BillRouteTableDao mBillRouteDao;

    private Handler checkTimeHandler = new Handler();
    /**
     * 间隔300秒(五分钟)，自动校验时间
     */
    private long loadTime = 1000 * 300;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isDoing) {
                //网络时间校验
                String compCode = SharedPreferUtil.getInstance().getCompanyCode();
                String empCode = SharedPreferUtil.getInstance().getWorkNum();
                String pwd = SharedPreferUtil.getInstance().getPwd();
                CheckNetTimeUtil.checkNetworkTime(LoadScanActivity.this, compCode, empCode, pwd, true, null);
            }
            // 间隔300秒(五分钟)
            checkTimeHandler.postDelayed(this, loadTime);
        }
    };

    @SuppressLint("HandlerLeak")
    private void setHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLER_100:
                        Bundle bundle = msg.getData();
                        String mm = bundle.getString("mm");
                        String ss = bundle.getString("ss");
                        deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                        if (deptType != 5 && deptType != 6) {
                            //网点
                            if ("30".equals(mm) && "00".equals(ss)) {
                                SoundVibratorManager.playVibrator(LoadScanActivity.this, 3000);
                                showToastTime("离规定发车时间还有30分钟！", 3000);
                            }
                        }
                        if (Integer.parseInt(mm) < 30) {
                            tvloadTime.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            tvloadTime.setTextColor(getResources().getColor(R.color.black));
                        }
                        tvloadTime.setText(mm + ":" + ss);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @SuppressLint("HandlerLeak")
    private Handler flashHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (flashCount < 0) {
                flashBtn.setText("刷新");
                flashBtn.setEnabled(true);
                return;
            }
            flashBtn.setText(flashCount + "");
            flashBtn.setEnabled(false);
        }
    };
    private Runnable falshRunnable = new Runnable() {
        @Override
        public void run() {
            flashCount--;
            flashHandler.sendEmptyMessage(0);
            if (flashCount < 0) {
                flashHandler.removeCallbacks(falshRunnable);
                return;
            }
            LogUtil.e(flashCount + "");
            //延迟一秒执行
            flashHandler.postDelayed(this, 1000);
        }
    };

    @Override
    public void handleBarCode(final String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号" + result + "扫描失败");
        } else {
            handleBarCodeResult(result, null);
        }
    }

    private void handleBarCodeResult(final String result, final ScanResult scanResult) {
        long scanLastTime = sharedPreferUtil.getLongValue(Common.SCAN_LAST_TIME);
        long currentTime = System.currentTimeMillis();
        if (isFirstScan || currentTime - scanLastTime > 1000 * 300) {
            isFirstScan = false;
            //每次进入界面校验网络时间,或者扫描时间超过五分钟
            String compCode = SharedPreferUtil.getInstance().getCompanyCode();
            String empCode = SharedPreferUtil.getInstance().getWorkNum();
            String pwd = SharedPreferUtil.getInstance().getPwd();
            CheckNetTimeUtil.checkNetworkTime(this, compCode, empCode, pwd, false, new UICallBack() {
                @Override
                public void onError(String msg) {
                    if (msg.equals(Constants.PLEASE_CHECK_NET)) {
                        startScan(result, scanResult);
                    }
                }

                @Override
                public void onSuccess(Object obj) {
                    startScan(result, scanResult);
                }
            });
        } else {
            startScan(result, scanResult);
        }
    }

    private void startScan(String result, ScanResult scanResult) {
        //融合装车扫描创建任务开关
        boolean scanSwitch = sharedPreferUtil.getBooleanValue(Constants.MERGE_LOAD_SCAN_TASK_SWITCH);
        if (scanSwitch) {
            //快运或者快递首次扫描，需创建装车任务
            if (!mYmScaned && (StringUtils.isWaybillNo(result) || StringUtils.isPackgeNo(result))) {
                createStowageNos(result, scanResult);
            } else if (!mUcScaned && UcWaybillValidate.validate(result)) {
                createStowageNos(result, scanResult);
            } else {
                doScan(result, scanResult);
            }
        } else {
            doScan(result, scanResult);
        }
    }

    private void createStowageNos(final String result, final ScanResult scanResult) {
        //组装装卸人
        final List<JoinPeopleEntity> joinPeoples = new ArrayList<>();
        deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (deptType == 5 || deptType == 6) {
            //分拨
            joinPeoples.addAll(mJoinPeopleEntityList);
        } else {
            //网点
            JoinPeopleEntity joinPeople = new JoinPeopleEntity();
            joinPeople.setUserCode(sharedPreferUtil.getValue(Common.USER_CODE));
            joinPeople.setUserName(sharedPreferUtil.getEmpName());
            joinPeoples.add(joinPeople);
        }

        int createType = 0;
        if (StringUtils.isWaybillNo(result) || StringUtils.isPackgeNo(result)) {
            //快运单号
            createType = 1;
        } else if (UcWaybillValidate.validate(result)) {
            //快递运单
            createType = 2;
        } else {
            doScan(result, scanResult);
            return;
        }

        List<CheckBoxItemEntity> nextDepts = new ArrayList<>();
        for (LoadInfo loadInfo : loadInfos) {
            if (result.startsWith(loadInfo.getWaybillNo())) {
                if (loadInfo.getNextDeptCode() == null) {
                    //运单无下一站，提示用户选择下一站
                    showSelectNextDept(result, scanResult, joinPeoples, createType);
                    return;
                }
                CheckBoxItemEntity entity = new CheckBoxItemEntity();
                entity.setCode(loadInfo.getNextDeptCode());
                entity.setName(loadInfo.getNextDeptName());
                nextDepts.add(entity);
                break;
            }
        }
        if (nextDepts.isEmpty()) {
            //下一站为空，说明没有匹配到运单，为强扫，提示用户选择下一站
            showSelectNextDept(result, scanResult, joinPeoples, createType);
        } else {
            createLoadTask(result, scanResult, nextDepts, joinPeoples, createType);
        }
    }

    private void createLoadTask(final String result, final ScanResult scanResult, List<CheckBoxItemEntity> mSelectNextDepts,
                                final List<JoinPeopleEntity> joinPeopleEntityList, int createType) {
        showPgDlg("创建中...");
        LoadUtil.createLoadTask(mSelectNextDepts, carPlanTaskEntityList, joinPeopleEntityList, createType, new UICallBack() {
            @Override
            public void onError(String msg) {
                dismissPgDlg();
                showToast(msg);
            }

            @Override
            public void onSuccess(Object obj) {
                dismissPgDlg();
                if (obj instanceof Boolean) {
                    //下一站没有都匹配到装车任务,调接口创建成功后，继续扫描
                    boolean isUpdateNextDept = (boolean) obj;
                    if (isUpdateNextDept) {
                        int res = new UnloadTaskTableDao().noExitInsert(UnloadTaskTable.parseUnloadTable2(task, carPlanTaskEntityList, 1), 1);
                        if (res >= 0) {
                            startDoScan(result, scanResult);
                        } else {
                            showToast("保存装车任务失败！");
                        }
                    } else {
                        //下一站都匹配到装车任务,无需创建，再判断有修改装卸人就调接口修改，没有继续扫描
                        addLoaderEmpCodes(result, scanResult, joinPeopleEntityList);
                    }
                }
            }
        });
    }

    private void showSelectNextDept(final String result, final ScanResult scanResult, final List<JoinPeopleEntity> joinPeopleEntityList, final int createType) {
        List<CheckBoxItemEntity> checkNextList = new ArrayList<>();
        if (carPlanTaskEntityList != null) {
            for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
                if (planTask.getNodes() != null) {
                    for (VehTaskNodeEntity node : planTask.getNodes()) {
                        CheckBoxItemEntity entity = new CheckBoxItemEntity();
                        if (planTask.getLoadTasks() != null) {
                            for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                                if (loadTask.getDestDeptCode().equals(node.getTaskNodeCode())) {
                                    entity.setCheck(true);
                                    entity.setTempCheck(true);
                                }
                            }
                        }
                        entity.setName(node.getTaskNodeName());
                        entity.setCode(node.getTaskNodeCode());
                        checkNextList.add(entity);
                    }
                }
            }
        }
        DialogUtil.Companion.checkBoxDialog(this, "选择下一站", "确定", "返回", checkNextList, true, carPlanTaskEntityList, new OnClickCallBack() {
            @Override
            public void onCancle() {
            }

            @Override
            public void onSure(Object obj, Object obj1) {
                List<CheckBoxItemEntity> nextDepts = (List<CheckBoxItemEntity>) obj;
                createLoadTask(result, scanResult, nextDepts, joinPeopleEntityList, createType);
            }
        });
    }

    /**
     * 修改装卸车参与人接口
     */
    private void addLoaderEmpCodes(final String result, final ScanResult scanResult, List<JoinPeopleEntity> joinPeoples) {
        //调用添加装卸人接口，然后跳转至卸车扫描界面
        showPgDlg("添加参与人中...");
        LoadUtil.addLoaderEmpCodes(joinPeoples, carPlanTaskEntityList, Common.SCAN_TYPE_MERGE_LOAD, platformNo,
                new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        int res = new UnloadTaskTableDao().noExitInsert(UnloadTaskTable.parseUnloadTable2(task, carPlanTaskEntityList, 1), 1);
                        if (res >= 0) {
                            doScan(result, scanResult);
                        } else {
                            showToast("保存装车任务失败！");
                        }
                    }
                });
    }

    private void startDoScan(String result, ScanResult scanResult) {
        //初始任务设置
        setInitTask();
        doScan(result, scanResult);
    }

    /**
     * 处理扫描
     *
     * @param result 扫描的运单
     */
    LoadBillTaskEntity ucLoadTask = null;
    boolean isBillRouteMatch = true; //路由单号是否匹配

    private synchronized void doScan(final String result, ScanResult scanResult) {
        //本地记录扫描最后时间
        sharedPreferUtil.setLongValue(Common.SCAN_LAST_TIME, System.currentTimeMillis());

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result) && !UcWaybillValidate.validate(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!(" + result + ")");
            return;
        }

        if (isUcOneTask && !UcWaybillValidate.validate(result)) {
            SoundVibratorManager.playSound(2);
            showToast("非快递运单号!(" + result + ")");
            return;
        }

        if (isYmOneTask && !StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("非快运单号!(" + result + ")");
            return;
        }
        //校验是否跨越的壹米运单规则
        if (isKuaYueTask && !StringUtils.isKyeYiMiWaybillNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("非同行货物，不能交接!(" + result + ")");
            return;
        }

        if (StringUtils.isWaybillNo(result) || StringUtils.isPackgeNo(result)) { //扫描快运单号
            //快运单号
            for (int i = 0; i < loadInfos.size(); i++) {
                final LoadInfo detailBillcode = loadInfos.get(i);
                if (!result.startsWith(detailBillcode.getWaybillNo())) {
                    // 判断主单是否相等
                    continue;
                }
                // 如果是大票货，只能添加000尾号的子单
                if (detailBillcode.isBigTicket() && !"000".equals(result.replace(detailBillcode.getWaybillNo(), ""))) {
                    showToast("(" + result + ")单号不符合规范，大票货子单尾号为000");
                    return;
                } else if (!detailBillcode.isBigTicket() && "000".equals(result.replace(detailBillcode.getWaybillNo(), ""))) {
                    showToast("(" + result + ")单号不符合规范，非大票货子单尾号不能为000");
                    return;
                }

                //运单根据配载单限重
                if (isWeightLimit(detailBillcode.isBigTicket(), detailBillcode.getWaybillNo(), result, detailBillcode.getStowageNo(), null)) {
                    return;
                }

                //分拨装车对改小的运单重量超出差值则提醒
                deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                if (deptType == 5 || deptType == 6) {
                    BigDecimal weightRate = detailBillcode.getWeightRate();
                    if (weightRate != null) {
                        if (weightRate.compareTo(BigDecimal.ZERO) < 0
                                && weightRate.abs().compareTo(new BigDecimal(mWeightDiff)) > 0) {
                            Context currentContext = ActivityStack.getInstance().currentActivity();
                            MyDialog dialog = new MyDialog(currentContext);
                            dialog.setIcon(R.drawable.alert);
                            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                            dialog.setTitle("提示");
                            dialog.setMessage("此运单重量改小" + weightRate.abs() + "%，存在偷重偷方可能，请进行复称复查！");
                            dialog.setPositiveClickListener("复称", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            final int finalI = i;
                            dialog.setNegativeClickListener(R.drawable.btn_login_selector, "强装", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    //继续处理扫描结果
                                    continueHandleScan(detailBillcode, result, finalI);
                                }
                            });
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.setCancelable(false);
                            dialog.show();
                            SoundVibratorManager.playSound(2);
                            return;
                        }
                    }
                }
                //继续处理扫描结果
                continueHandleScan(detailBillcode, result, i);
                return;
            }
            //子单下载主单
            downloadWaybillNo(result);
        } else if (UcWaybillValidate.validate(result)) {
            //快递单号

            //判断是否是截留件
            if (Common.isJieLiuJian(this, result, mJieLiuJianTableDao)) {
                return;
            }

            //匹配到下一站的快递任务
            ucLoadTask = null;
            Boolean isQueryBillRoute = false;
            isBillRouteMatch = true;
            try {
                BillRouteTable billRouteTable = mBillRouteDao.findDataByBillCode(result);
                if (billRouteTable != null) {
                    //运单路由错发标志
                    isQueryBillRoute = true;
                    isBillRouteMatch = true;
                    boolean isChuoFa = true;
                    for (CarPlanTaskEntity entity : carPlanTaskEntityList) {
                        if (entity.getLoadTasks() != null) {
                            for (LoadBillTaskEntity loadTask : entity.getLoadTasks()) {
                                if (!loadTask.getStowageNo().startsWith("P")) {
                                    if (billRouteTable.getEndStationCode().equals(loadTask.getDestDeptCode())) {
                                        isChuoFa = false;
                                        loadTask.setTaskNo(entity.getTaskNo());
                                        ucLoadTask = loadTask;
                                    }
                                }
                            }
                        }
                    }
                    if (isUcCuoFenSwitch && isChuoFa) {
                        //下一站不相等，则提示
                        isBillRouteMatch = false;
                        isQueryBillRoute = false;
                        MyDialog.showAlertDialog(this, null, "单号【" + result
                                + "】下一站与规定下一站【" + billRouteTable.getEndStationName() + "】不一致，请确认", "好的");
                        SoundVibratorManager.playSound(5);
                    }
                } else {
                    isBillRouteMatch = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            judgeIsShowSelectDialog(result, isQueryBillRoute);
        } else {
            showToast("未知运单号！");
        }
    }


    private void dealScan(final String result, LoadBillTaskEntity ucLoadTask) {
        if (UcWaybillValidate.isUcChildWyabill(result)) {
            //快递子单，一票多件
            final Iterator<LoadInfo> it = loadInfos.iterator();
            while (it.hasNext()) {
                final LoadInfo loadinfo = it.next();
                for (QueryLoadDetailChildBillcode child : loadinfo.getChildList()) {
                    if (child.getChildWaybillNo().equals(result)) {
                        if (child.getFlag() == 1) {
                            if (!FastClick.isFastClickScanner()) {
                                //重复扫描提示
                                SoundVibratorManager.playSound(2);
                                Context currentContext = ActivityStack.getInstance().currentActivity();
                                LoadUtil.showDeleteWaybillDialog(currentContext, result, loadinfo, 11, carPlanTaskEntityList, 1,
                                        new UICallBack() {
                                            @Override
                                            public void onError(String msg) {

                                            }

                                            @Override
                                            public void onSuccess(Object obj) {

                                                //移除列表中的运单
                                                if (loadinfo.getScanCount() == 0) {
                                                    it.remove();
                                                }

                                                //根据复选框类型显示运单列表
                                                showInfosByCheckBox();
                                            }
                                        });
                            }
                            return;
                        }
                    }
                }
            }

            final LoadBillTaskEntity finalUcLoadTask = ucLoadTask;
            OneToMoreModule.getInstance().queryMainScanCodeBySon(result, new ConnectionResultLister<SonScanStatictisBan>() {

                @Override
                public void getResult(int errorCode, SonScanStatictisBan o) {
                    if (o != null) {
                        final Iterator<LoadInfo> it = loadInfos.listIterator();
                        while (it.hasNext()) {
                            final LoadInfo loadinfo = it.next();
                            if (loadinfo.getWaybillNo().equals(o.mainScanCode)) {
                                loadinfo.setSrcPiecesNum(o.sonScanCodeNumber + 1);
                                //添加UC快递子单
                                addChildScanCodelist(o.childScanCodeList, loadinfo, result, finalUcLoadTask);
                                //获取装卸组信息
                                getGroupInfo();
                                setLoadInfoMerge(loadinfo);
                                //设置开单件数
                                //插入表
                                saveUcWaybill(loadinfo, result, finalUcLoadTask, new Subscriber<Void>() {

                                    @Override
                                    public void onCompleted() {
                                        it.remove();
                                        SoundVibratorManager.playSound(1);
                                        loadInfos.add(0, loadinfo);
                                        //根据复选框类型显示运单列表
                                        showInfosByCheckBox();
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        ToastUtil.showToast(e.getMessage());
                                    }

                                    @Override
                                    public void onNext(Void aVoid) {

                                    }
                                });
                                return;
                            }
                        }
                        continueHandleUcScan(o.mainScanCode, result, o.sonScanCodeNumber + 1, finalUcLoadTask);
                    } else {
                        for (LoadInfo item : loadInfos) {
                            if (item.getWaybillNo().equals(result)) {
                                for (QueryLoadDetailChildBillcode child : item.getChildList()) {
                                    child.setFlag(1);
                                    setLoadInfoMerge(item);
                                    //插入表
                                    saveUcWaybill(item, result, finalUcLoadTask, new Subscriber<Void>() {

                                        @Override
                                        public void onCompleted() {
                                            SoundVibratorManager.playSound(1);
                                            //根据复选框类型显示运单列表
                                            showInfosByCheckBox();
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            ToastUtil.showToast(e.getMessage());
                                        }

                                        @Override
                                        public void onNext(Void aVoid) {

                                        }
                                    });
                                    return;
                                }
                            }
                        }

                        continueHandleUcScan(result, result, 1, finalUcLoadTask);
                    }
                }
            });
        } else {
            //快递主单，一票一件
            final Iterator<LoadInfo> it = loadInfos.iterator();
            while (it.hasNext()) {
                final LoadInfo loadinfo = it.next();
                if (result.equals(loadinfo.getWaybillNo())) {
                    for (QueryLoadDetailChildBillcode child : loadinfo.getChildList()) {
                        if (child.getChildWaybillNo().equals(result)) {
                            if (child.getFlag() == 1) {
                                if (!FastClick.isFastClickScanner()) {
                                    SoundVibratorManager.playSound(2);
                                    //重复扫描提示
                                    Context currentContext = ActivityStack.getInstance().currentActivity();
                                    LoadUtil.showDeleteWaybillDialog(currentContext, result, loadinfo, 11, carPlanTaskEntityList, 1,
                                            new UICallBack() {
                                                @Override
                                                public void onError(String msg) {

                                                }

                                                @Override
                                                public void onSuccess(Object obj) {
                                                    //移除列表中的运单
                                                    if (loadinfo.getScanCount() == 0) {
                                                        it.remove();
                                                    }

                                                    //根据复选框类型显示运单列表
                                                    showInfosByCheckBox();
                                                }
                                            });
                                }
                                return;
                            }

                            child.setFlag(1);
                            //插入表
                            setLoadInfoMerge(loadinfo);
                            saveUcWaybill(loadinfo, result, ucLoadTask, new Subscriber<Void>() {

                                @Override
                                public void onCompleted() {
                                    SoundVibratorManager.playSound(1);
                                    //根据复选框类型显示运单列表
                                    showInfosByCheckBox();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    ToastUtil.showToast(e.getMessage());
                                }

                                @Override
                                public void onNext(Void aVoid) {

                                }
                            });
                            return;
                        }
                    }

                    if (loadinfo.getSrcPiecesNum() > 1) {
                        loadinfo.getChildList().add(createUcChildWaybill(result, ucLoadTask));
                    } else {
                        loadinfo.setSrcPiecesNum(1);
                        List<QueryLoadDetailChildBillcode> childBillcodeList = new ArrayList<>();
                        //添加UC快递子单
                        childBillcodeList.add(createUcChildWaybill(result, ucLoadTask));
                        loadinfo.setChildList(childBillcodeList);
                    }
                    setLoadInfoMerge(loadinfo);
                    //插入表
                    saveUcWaybill(loadinfo, result, ucLoadTask, new Subscriber<Void>() {

                        @Override
                        public void onCompleted() {
                            SoundVibratorManager.playSound(1);
                            //根据复选框类型显示运单列表
                            showInfosByCheckBox();
                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastUtil.showToast(e.getMessage());
                        }

                        @Override
                        public void onNext(Void aVoid) {

                        }
                    });

                    return;
                }
            }
            continueHandleUcScan(result, result, 1, ucLoadTask);
        }
    }


    private void setLoadInfoMerge(LoadInfo loadInfo) {
        if (kuaidiMerge == 1) {
            if (!isBillRouteMatch) {
                loadInfo.setIsChangeDest(1);
            }
        }

    }


    /****
     *
     * @param isSelectScanCode 是否匹配到了路由单号
     */
    public void judgeIsShowSelectDialog(final String result, boolean isSelectScanCode) {
        String switchState = sharedPreferUtil.getValue(SharedPreferUtil.KUAIDI_MERGE_LOAD_SWITCH);
        if ("1".equals(switchState)) { //1代表开 0代表关
            isBillRouteMatch = true;
            if (ucLoadTask == null || !isSelectScanCode) {
                //没有匹配到下一站的快递任务，则设置为默认第一个快递装车任务
                List<LoadBillTaskEntity> loadBillTaskEntityList = new ArrayList<>();
                for (int i = 0; i < carPlanTaskEntityList.size(); i++) {
                    if (!ArrayUtils.isEmpty(carPlanTaskEntityList.get(i).getLoadTasks())) {
                        for (int j = 0; j < carPlanTaskEntityList.get(i).getLoadTasks().size(); j++) {
                            if (carPlanTaskEntityList.get(i).getLoadTasks().get(j) != null && carPlanTaskEntityList.get(i).getLoadTasks().get(j).isCheck()) {
                                loadBillTaskEntityList.add(carPlanTaskEntityList.get(i).getLoadTasks().get(j));
                            }
                        }

                    }
                }
                if (!ArrayUtils.isEmpty(loadBillTaskEntityList)) {
                    for (int i = 0; i < loadBillTaskEntityList.size(); i++) {
                        loadBillTaskEntityList.get(i).setCheck(false);
                    }
                }
                disableScan();
                SoundVibratorManager.playSound(2);
                DialogUtil.Companion.showUnOrLoadTask(LoadScanActivity.this, loadBillTaskEntityList, 1, new OnClickCallBack() {
                    @Override
                    public void onCancle() {

                    }

                    @Override
                    public void onSure(Object obj, Object obj1) {

                    }


                    @Override
                    public void onSuccess(Object obj) {
                        super.onSuccess(obj);
                        enableScan();
                        if (LoadBillTaskEntity.class.isInstance(obj)) {
                            LoadBillTaskEntity loadBillTaskEntity = (LoadBillTaskEntity) obj;
                            ucLoadTask = loadBillTaskEntity;
                            dealScan(result, ucLoadTask);
                        }
                    }
                });
            } else {
                if (ucLoadTask == null) {
                    //没有匹配到下一站的快递任务，则设置为默认第一个快递装车任务
                    ucLoadTask = mUcLoadTask;
                }
                dealScan(result, ucLoadTask);
            }
        } else {
            if (ucLoadTask == null) {
                //没有匹配到下一站的快递任务，则设置为默认第一个快递装车任务
                ucLoadTask = mUcLoadTask;
            }
            if (kuaidiMerge == 0) { //判断快递是否合并装车 1代表合并 0代表不合并
                isBillRouteMatch = true;
            }
            dealScan(result, ucLoadTask);
        }
    }


    public void addChildScanCodelist(List<String> childList, LoadInfo loadInfo, String result, LoadBillTaskEntity finalUcLoadTask) {
        if (!ArrayUtils.isEmpty(childList)) {
            if (childList.size() > loadInfo.getChildList().size()) { //如果子单集合和服务器的子单集合不一致则循环遍历添加进子单集合
                for (int i = 0; i < childList.size(); i++) {
                    boolean isContains = false;
                    for (int j = 0; j < loadInfo.getChildList().size(); j++) {
                        //循环遍历子单集合和已扫描过的子单作对比
                        if (childList.get(i).equals(loadInfo.getChildList().get(j).getChildWaybillNo())) {
                            if (loadInfo.getChildList().get(j).getChildWaybillNo().equals(result)) {
                                loadInfo.getChildList().get(j).setFlag(1);
                            }
                            isContains = true;
                            break;
                        }
                    }
                    //如果已扫描过的子单集合没有包含子单集合,则添加到子单集合里
                    if (!isContains) {
                        loadInfo.getChildList().add(createUcChildWaybill(childList.get(i), result, finalUcLoadTask));
                    }
                }
            } else { //否则相等
                for (int j = 0; j < loadInfo.getChildList().size(); j++) {
                    //循环遍历子单集合和已扫描过的子单作对比
                    if (result.equals(loadInfo.getChildList().get(j).getChildWaybillNo())) {
                        loadInfo.getChildList().get(j).setFlag(1);
                        break;
                    }
                }
            }

        } else {
            loadInfo.getChildList().add(createUcChildWaybill(result, finalUcLoadTask));
        }
    }


    /**
     * 继续处理快递扫描结果
     *
     * @param waybillNo      主单号
     * @param childWaybillNo 子单号
     * @param ucLoadTask     匹配到的下一站快递任务
     */
    private void continueHandleUcScan(final String waybillNo, final String childWaybillNo, int srcPiecesNum, LoadBillTaskEntity ucLoadTask) {

        final LoadInfo loadInfo = new LoadInfo();
        loadInfo.setStowageNo(ucLoadTask.getStowageNo());
        loadInfo.setCarMark(ucLoadTask.getTaskNo());
        loadInfo.setWaybillNo(waybillNo);
        loadInfo.setStowageNo(ucLoadTask.getStowageNo());
        //设置为快递类型运单
        loadInfo.setWaybillType(2);
        setLoadInfoMerge(loadInfo);
        //设置开单件数
        loadInfo.setSrcPiecesNum(srcPiecesNum);
        List<QueryLoadDetailChildBillcode> childBillcodeList = new ArrayList<>();
        //添加UC快递子单
        childBillcodeList.add(createUcChildWaybill(childWaybillNo, ucLoadTask));
        loadInfo.setChildList(childBillcodeList);
        //获取装卸组信息
        getGroupInfo();
        //插入表
        saveUcWaybill(loadInfo, childWaybillNo, ucLoadTask, new Subscriber<Void>() {

            @Override
            public void onCompleted() {
                SoundVibratorManager.playSound(1);
                loadInfos.add(0, loadInfo);
                //根据复选框类型显示运单列表
                showInfosByCheckBox();
                mUcScaned = true;

                //发送消息处理手动添加结果
                ScanResult scanResult = new ScanResult(childWaybillNo, 6, 5);
                scanResult.setWaybillNo(waybillNo);
                EventBus.getDefault().post(scanResult);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(e.getMessage());
            }

            @Override
            public void onNext(Void aVoid) {

            }
        });
    }


    private QueryLoadDetailChildBillcode createUcChildWaybill(String childWaybillNo, LoadBillTaskEntity ucLoadTask) {
        return createUcChildWaybill(null, childWaybillNo, ucLoadTask);
    }

    /**
     * 创建快递子单对象
     */
    private QueryLoadDetailChildBillcode createUcChildWaybill(String fromServerChildNo, String childWaybillNo, LoadBillTaskEntity ucLoadTask) {
        QueryLoadDetailChildBillcode childBillcode = new QueryLoadDetailChildBillcode();
        childBillcode.setChildWaybillNo(childWaybillNo);
        //服务器子单集合和扫描过的子单集合做对比，并且比对扫描数据
        if (fromServerChildNo != null && fromServerChildNo.equals(childWaybillNo)) {
            childBillcode.setFlag(1);
        } else if (fromServerChildNo == null) { //扫描到的数据作对比
            childBillcode.setFlag(1);
        }
        childBillcode.setStowageNo(ucLoadTask.getStowageNo());
        return childBillcode;
    }

    /**
     * 保存快递扫描单号
     */
    private void saveUcWaybill(LoadInfo loadInfo, String childWaybillNo, LoadBillTaskEntity ucLoadTask,
                               Subscriber<Void> subscriber) {
        //插入表
        final UnloadScanTable scanTable =
                new UnloadScanTable(ucLoadTask.getStowageNo(), loadInfo.getWaybillNo(), childWaybillNo, null,
                        ucLoadTask.getStowageNo(), operTypeCode, inputType, "", "",
                        SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().getValue(Common.USER_NAME),
                        Constants.GetSysTime(), Constants.GetScanTime(), SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE),
                        SysInfo.getInstance().getImei(), ucLoadTask.getCarNo(), 0, null, "", joinWrokNum, joinUserName,
                        //waybillType：1-快运，2-快递
                        deptType, null, platformNo, null, 2, loadInfo.getCarMark(), null, null, loadInfo.getIsChangeDest());
        scanTable.setTaskNo(ucLoadTask.getTaskNo());
        scanTable.setRelationDeptCode(ucLoadTask.getDestDeptCode());
        scanTable.setRelationDeptName(ucLoadTask.getDestDeptName());
        scanTable.setRelationDeptType(ucLoadTask.getRelationDeptType());
        scanTable.setSrcPiecesNum(loadInfo.getSrcPiecesNum());

        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                try {
                    if (mUnloadScanTableDao.insert(scanTable) <= 0) {
                        SoundVibratorManager.playSound(2);
                        subscriber.onError(new Throwable("插入数据库失败！"));
                        return;
                    }
                } catch (SQLException e) {
                    LogUtil.e(e.toString());
                    SoundVibratorManager.playSound(2);
                    subscriber.onError(new Throwable("保存装车数据异常：" + e.toString()));
                    return;
                }
                //设置最近扫描时间
                FastClick.setLastClickTimeScanner();
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);

    }


    /**
     * 继续处理扫描结果
     */
    private void continueHandleScan(LoadInfo detailBillcode, String result, int index) {
        if (detailBillcode.getChildList() != null && !detailBillcode.getChildList().isEmpty()) {
            QueryLoadDetailChildBillcode tempDetailChildBillcode = null;
            for (QueryLoadDetailChildBillcode detailChildBillcode : detailBillcode.getChildList()) {
                if (result.equals(detailChildBillcode.getChildWaybillNo())) {
                    // 找到相同的子单
                    tempDetailChildBillcode = detailChildBillcode;
                    break;
                }
            }
            if (tempDetailChildBillcode != null) {
                /**判断该子单号是否已打印，未打印给出提示，并且禁止扫描*/
                boolean isBePrint = isBePrintChileWayBillForLoad(detailBillcode, tempDetailChildBillcode);
                if (!isBePrint) {
                    return;
                }
            }

            if (tempDetailChildBillcode == null) {
                detailBillcode.setRemark("2");
                //创建子单实体
                tempDetailChildBillcode = new QueryLoadDetailChildBillcode();
                tempDetailChildBillcode.setChildWaybillNo(result);
                //设置已扫描
                tempDetailChildBillcode.setFlag(1);
                //将子单实体添加到子单列表中
                detailBillcode.getChildList().add(tempDetailChildBillcode);
            } else if (tempDetailChildBillcode.getFlag() == 1) {
                if (!FastClick.isFastClickScanner()) {
                    //重复扫描提示
                    SoundVibratorManager.playSound(2);
                    Context currentContext = ActivityStack.getInstance().currentActivity();
                    LoadUtil.showDeleteWaybillDialog(currentContext, result, detailBillcode, 11, carPlanTaskEntityList, 1,
                            new UICallBack() {
                                @Override
                                public void onError(String msg) {

                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    //根据复选框类型显示运单列表
                                    showInfosByCheckBox();
                                }
                            });
                }
                return;
            } else {
                //设置已扫描
                tempDetailChildBillcode.setFlag(1);
            }

            //库存件数为0则为强扫
            String remark = "";
            if (detailBillcode.getPiecesNum() == null || detailBillcode.getPiecesNum() == 0) {
                remark = "2";
            }

            //获取装卸组信息
            getGroupInfo();

            int goodsPriority = 0;
            if (detailBillcode.getGoodsPriority() != null) {
                goodsPriority = Integer.parseInt(detailBillcode.getGoodsPriority());
            }

            if (detailBillcode.getStowageNo() == null && carPlanTaskEntityList != null) {
                for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
                    if (planTask.getLoadTasks() != null) {
                        for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                            if (loadTask.getDestDeptCode().equals(detailBillcode.getRelationDeptCode())) {
                                detailBillcode.setStowageNo(loadTask.getStowageNo());
                                detailBillcode.setTask(loadTask.getStowageNo());
                                break;
                            }
                        }
                    }
                }
            }

            //插入表
            UnloadScanTable scanTable =
                    new UnloadScanTable(detailBillcode.getTask(), detailBillcode.getWaybillNo(), result, detailBillcode.getPackageNo(),
                            detailBillcode.getStowageNo(), operTypeCode, inputType, remark, detailBillcode.getAreaCode(),
                            SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().getValue(Common.USER_NAME),
                            Constants.GetSysTime(), Constants.GetScanTime(), SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE),
                            SysInfo.getInstance().getImei(), detailBillcode.getCarNo(), 0, goodsPriority, detailBillcode.getProductType(), joinWrokNum, joinUserName,
                            //waybillType：1-快运，2-快递
                            deptType, null, platformNo, null, 1, detailBillcode.getCarMark(), null, null);
            scanTable.setTaskNo(detailBillcode.getTask());
            scanTable.setRelationDeptCode(detailBillcode.getRelationDeptCode());
            scanTable.setRelationDeptName(detailBillcode.getRelationDeptName());
            scanTable.setRelationDeptType(detailBillcode.getRelationDeptType());
            scanTable.setSrcPiecesNum(detailBillcode.getSrcPiecesNum());
            try {
                if (mUnloadScanTableDao.insert(scanTable) <= 0) {
                    SoundVibratorManager.playSound(2);
                    ToastUtil.showToast("插入数据库失败！");
                    return;
                }
            } catch (SQLException e) {
                LogUtil.e(e.toString());
                showToast("保存装车数据异常：" + e.toString());
                return;
            }

            loadInfos.remove(index--);
            Context currentContext = ActivityStack.getInstance().currentActivity();
            if (currentContext instanceof LoadScanActivity) {
                SoundVibratorManager.playSound(1);
            }
            loadInfos.add(0, detailBillcode);
            //根据复选框类型显示运单列表
            showInfosByCheckBox();
            //只分拨提醒动态路由提醒
            int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
            if (deptType == 5 || deptType == 6) {
                String dynamicRoute = detailBillcode.getDynamicRoute();
                if (dynamicRoute != null) {
                    //当前分拨等于动态路由的第一个分拨，则提醒用户
                    String currDeptCode = sharedPreferUtil.getDeptCode();
                    String[] dyRoute = dynamicRoute.split("-");
                    if (dyRoute.length > 0 && currDeptCode.equals(dyRoute[0])) {
                        showToast("动态路由推荐");
                    }
                }
            }
            //发送消息处理手动添加结果
            EventBus.getDefault().post(new ScanResult(result, 6, 5));
            mYmScaned = true;
            //设置最近扫描时间
            FastClick.setLastClickTimeScanner();
        }
    }

    /**
     * 已扫配载单重量
     */
    private double scanedWeight(String result, String stowageNo) {
        double sweight = 0.0;
        int count;
        // 遍历下拉下来的每个运单
        for (LoadInfo billDto : loadInfos) {
            if (stowageNo.equals(billDto.getStowageNo())) {
                if (result.startsWith(billDto.getWaybillNo())) {
                    // 主单相等
                    count = billDto.getScanCount() + 1;
                } else {
                    //主单不相等
                    count = billDto.getScanCount();
                }
                //统计已扫描的数量
                if (count > 0) {
                    //大票货
                    if ((billDto.getWaybillNo() + "000").equals(billDto.getChildList().get(0).getChildWaybillNo())) {
                        sweight += BigDecimalUtils.round(billDto.getWeight().doubleValue(), 4);
                    } else {
                        //普通货
                        sweight += BigDecimalUtils.mul(BigDecimalUtils.div(billDto.getWeight().doubleValue(), billDto.getSrcPiecesNum(), 4), count);
                    }
                }
            }
        }
        return BigDecimalUtils.round(sweight, 2);
    }

    /**
     * 判断该子单号是否已打印，未打印给出提示，并且禁止扫描
     *
     * @param childBean 子单实体
     */
    private boolean isBePrintChileWayBillForLoad(LoadInfo detailBillcode, QueryLoadDetailChildBillcode childBean) {
        if (childBean.getBePrint() == null || childBean.getBePrint() == 2) {
            //字段为2或者空-已打印
            return true;
        } else if (childBean.getBePrint() == 1) {
            SpannableString mStyledText = new SpannableString("该票货发生目的站更改，请补打标签更换！");
            //mStyledText.setSpan(new ForegroundColorSpan(Color.RED), 11, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            //1-未打印，禁止扫描
            //设置该标志，不返回扫描结果
//            MyDialog.setTag(1);
            MyDialog dialog = MyDialog.getInstance(this);
            dialog.setIcon(R.drawable.alert);
            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
            dialog.setTitle("系统提示");
            dialog.setText(mStyledText);
            dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    MyDialog.setNull();
                }
            });
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            if (detailBillcode.getScanCount() == 0) {
                //扫描第一件做打断提示
                //设置该标志，不返回扫描结果
//                MyDialog.setTag(1);
                try {
                    dialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        }
        return true;
    }

    /**
     * 获取动态路由的运单号
     *
     * @param waybillNo 运单号
     */
    private void getDynamicRouteWaybillNo(String waybillNo) {
        Map<String, String> params = new HashMap<>(1);
        params.put("waybillNo", waybillNo);

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .setUrl(Constants.URL_FORCE_SCAN)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {

                    }

                    @Override
                    public void onSuccess(Object obj) {

                    }
                });
    }

    /**
     * 子单下载主单
     */
    private void downloadWaybillNo(final String result) {
        //关闭扫描
        disableScan();
        showPgDlg("正在子单下载主单...");

        //扫描数据上传完后  调完成任务
        QueryWaybillByChildNoRequest mQueryWaybillByChildNoRequest = new QueryWaybillByChildNoRequest();
        mQueryWaybillByChildNoRequest.setChildWaybillNo(result);

        Map<String, String> params = new HashMap<>(1);
        params.put("childWaybillNo", result);

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .setUrl(Constants.URL_FORCE_SCAN)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        enableScan();
                        dismissPgDlg();
                        if (msg.equals(Constants.PLEASE_CHECK_NET)) {
                            merge(null, result, true, mYmLoadTask);
                        } else {
                            SoundVibratorManager.playSound(2);
                            showToast(msg);
                            //显示强扫错误中止扫描提示对话框
                            showForceScanErrorDialog(msg);
                        }

                    }

                    @Override
                    public void onSuccess(Object obj) {
                        enableScan();

                        if (obj instanceof QueryWaybillByChildNoResponse) {
                            final QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
                            dismissPgDlg();
                            //路由验证
                            if (response.getData() == null) {
                                showToast("(" + result + ")子单下载主单数据为空");
                                return;
                            }
                            boolean isRouteWrong = true;
                            if (carPlanTaskEntityList != null) {
                                for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
                                    if (planTask.getLoadTasks() != null) {
                                        for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                                            if (loadTask.isCheck()) {
                                                //校验是否路由错分，参数：返回的路由，下一站，当前站
                                                if (!Common.waybillRouteWrongForLoad(response.getData().getRouteCode(), loadTask.getDestDeptCode(), loadTask.getSrcDeptCode())) {
                                                    isRouteWrong = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //获取串货运单的下一站和配载任务的下一站相同的装车任务
                            LoadBillTaskEntity loadTaskEntity = null;
                            String routeCode = response.getData().getRouteCode();
                            if (routeCode != null) {
                                String[] routeCodeSplit = routeCode.split(sharedPreferUtil.getDeptCode());
                                if (routeCodeSplit.length > 1) {
                                    if (carPlanTaskEntityList != null) {
                                        for (CarPlanTaskEntity entity : carPlanTaskEntityList) {
                                            if (entity.getLoadTasks() != null) {
                                                for (LoadBillTaskEntity loadTask : entity.getLoadTasks()) {
                                                    if (loadTask.isCheck() && loadTask.getStowageNo().startsWith("P")) {
                                                        String nextCode = loadTask.getDestDeptCode();
                                                        if (routeCodeSplit[1].startsWith("-" + nextCode)) {
                                                            //获取下一站相同的装车任务
                                                            loadTaskEntity = loadTask;
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //运单根据配载单限重
                            String stowageNo;
                            if (loadTaskEntity != null) {
                                stowageNo = loadTaskEntity.getStowageNo();
                            } else {
                                stowageNo = carCode;
                                loadTaskEntity = mYmLoadTask;
                            }
                            String waybillNo = String.format("%s", response.getData().getWaybillNo());
                            if (isWeightLimit(false, waybillNo, result, stowageNo, response.getData())) {
                                return;
                            }

                            if (!isRouteWrong) {
                                //合并数据到内存，并插入当前条码到数据库
                                merge(response.getData(), result, false, loadTaskEntity);
                            } else {
                                if (isFinishing()) {
                                    return;
                                }
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                    dialog = null;
                                }
                                dialog = new MyDialog(LoadScanActivity.this);
                                dialog.setIcon(R.drawable.alert);
                                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                                dialog.setTitle("系统提示");
                                dialog.setMessage("请核对正确目的站是否装车？(" + result + ")");
                                final LoadBillTaskEntity finalLoadTaskEntity = loadTaskEntity;
                                dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        //合并数据到内存，并插入当前条码到数据库
                                        merge(response.getData(), result, true, finalLoadTaskEntity);
                                    }
                                });
                                dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        //串货取消记录提交
                                        chuanHuoCancelRecordSubmit(response.getData(), result, true, finalLoadTaskEntity);
                                    }
                                });
                                boolean isCheck = sharedPreferUtil.getBooleanValue(Common.LOAD_WRONG_FORCE_SURE);
                                if (isCheck) {
                                    dialog.setButtonEnable(false);
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            dialog.dismiss();
                                            //合并数据到内存，并插入当前条码到数据库
                                            merge(response.getData(), result, true, finalLoadTaskEntity);
                                        }
                                    }, 2 * 1000);
                                } else {
                                    dialog.setButtonEnable(true);
                                }
                                try {
                                    dialog.show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                SoundVibratorManager.playSound(2);
                            }
                        }
                    }
                });
    }

    /**
     * 运单根据配载单限重
     *
     * @return true
     */
    private boolean isWeightLimit(boolean isBigTicket, String waybillNo, String childWaybillNo, String stowageNo, WaybillInfo waybillInfo) {
        //支线校验车型限重开关，如果开启，再校验额定载重是否超过维护倍数的重量，超过则打断提醒，不能继续装车(大票货不限重)
        if (mLimitWeightStowage != null && !isBigTicket && !"000".equals(childWaybillNo.replace(waybillNo, ""))) {
            for (CarModelLimitWeightEntity limitWeightEntity : mLimitWeightStowage) {
                //始发支线限重
                if (stowageNo.equals(limitWeightEntity.getStowageNo())
                        && limitWeightEntity.getBizTypeCode() == 2
                        && limitWeightEntity.isStartDept()) {
                    if (limitWeightEntity.getLimitWeight() != null) {
                        //限载重量
                        double limitWeight = Double.parseDouble(limitWeightEntity.getLimitWeight()) * limitWeightEntity.getMultiple();
                        //已扫配载单的重量
                        double scanedWeight;
                        if (waybillInfo != null) {
                            scanedWeight = BigDecimalUtils.round(waybillInfo.getRealWeight().doubleValue(), 2);
                        } else {
                            scanedWeight = scanedWeight(childWaybillNo, stowageNo);
                        }
                        if (scanedWeight > limitWeight) {
                            MyDialog.showAlertDialog(this, "车辆配载重量已超过该车型额定重量，禁止装车！(" + stowageNo + ")");
                            SoundVibratorManager.playSound(2);
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 串货取消记录提交
     */
    private void chuanHuoCancelRecordSubmit(WaybillInfo data, String result, boolean isQiangScan, LoadBillTaskEntity loadTaskEntity) {
        //构建数据
        Map maps = getChuanHuoData(data, result, isQiangScan, loadTaskEntity);
        UnloadScanTable mUnloadScanTable = (UnloadScanTable) maps.get(FINAL_UNLOAD_SCAN_TABLE);
        //串货取消记录标记
        mUnloadScanTable.setOperTypeCode(3);

        List<UnloadScanTable> list = new ArrayList<>();
        list.add(mUnloadScanTable);
        ScanLoadUploadRequest mScanLoadUploadRequest = new ScanLoadUploadRequest();
        mScanLoadUploadRequest.setRecords(list);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(Object.class)
                .setUrl(Constants.URL_UPLOAD_DATA_OPER_RECORD)
                .setRequestObject(mScanLoadUploadRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e("串货取消记录提交-->" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        LogUtil.e("串货取消记录上传成功！");
                    }
                });
    }

    /**
     * 合并数据到内存，并插入当前条码到数据库
     */
    private void merge(WaybillInfo data, String result, boolean isQiangScan, LoadBillTaskEntity loadTaskEntity) {
        //构建数据
        Map maps = getChuanHuoData(data, result, isQiangScan, loadTaskEntity);
        UnloadScanTable mUnloadScanTable = (UnloadScanTable) maps.get(FINAL_UNLOAD_SCAN_TABLE);
        LoadInfo mQueryLoadDetailBillcode = (LoadInfo) maps.get(FINAL_LOAD_INFO);
        try {
            if (mUnloadScanTableDao.insert(mUnloadScanTable) <= 0) {
                SoundVibratorManager.playSound(2);
                Toast.makeText(this, "插入数据库失败！", Toast.LENGTH_LONG).show();
                return;
            }
        } catch (SQLException e) {
            showToast("装车强扫插入数据失败：" + e.toString());
            return;
        }

        SoundVibratorManager.playSound(1);
        loadInfos.add(0, mQueryLoadDetailBillcode);
        //根据复选框类型显示运单列表
        showInfosByCheckBox();
        mYmScaned = true;
        //设置最近扫描时间
        FastClick.setLastClickTimeScanner();
    }

    /**
     * 构建串货数据
     */
    private Map<String, Object> getChuanHuoData(WaybillInfo data, String result,
                                                boolean isQiangScan, LoadBillTaskEntity loadTaskEntity) {
        LoadInfo mQueryLoadDetailBillcode = new LoadInfo();
        mQueryLoadDetailBillcode.setCarMark(loadTaskEntity.getTaskNo());
        mQueryLoadDetailBillcode.setRemark("2");
        if (data != null) {
            mQueryLoadDetailBillcode.setWaybillNo(data.getWaybillNo() + "");
            mQueryLoadDetailBillcode.setSrcPiecesNum(data.getQuantity());
            mQueryLoadDetailBillcode.setPiecesNum(data.getNowInventory());
            mQueryLoadDetailBillcode.setWeight(data.getRealWeight());
            mQueryLoadDetailBillcode.setVolume(data.getVolume());
            mQueryLoadDetailBillcode.setChargedWeight(data.getChargeableWeight());
            mQueryLoadDetailBillcode.setWaybillRoute(data.getRouteCode());
        } else {
            mQueryLoadDetailBillcode.setWaybillNo(result.substring(0, 12));
        }
        mQueryLoadDetailBillcode.setPackageNo("");
        mQueryLoadDetailBillcode.setAreaCode("");
        mQueryLoadDetailBillcode.setBillType(1);
        mQueryLoadDetailBillcode.setRelationDeptCode(loadTaskEntity.getDestDeptCode());
        mQueryLoadDetailBillcode.setRelationDeptName(loadTaskEntity.getDestDeptName());
        mQueryLoadDetailBillcode.setRelationDeptType(loadTaskEntity.getRelationDeptType());
        if (loadTaskEntity != null) {
            mQueryLoadDetailBillcode.setTask(loadTaskEntity.getStowageNo());
            mQueryLoadDetailBillcode.setStowageNo(loadTaskEntity.getStowageNo());
            mQueryLoadDetailBillcode.setCarNo(loadTaskEntity.getCarNo());
        } else {
            mQueryLoadDetailBillcode.setTask(carCode);
            mQueryLoadDetailBillcode.setStowageNo(carCode);
            mQueryLoadDetailBillcode.setCarNo(carNo);
        }
        //设置强扫串货标志
        if (isQiangScan) {
            mQueryLoadDetailBillcode.setGoodsPriority("2");
        }

        List<QueryLoadDetailChildBillcode> childList = new ArrayList<>();
        //大票货
        if (result.endsWith("000")) {
            QueryLoadDetailChildBillcode mQueryLoadDetailChildBillcode = new QueryLoadDetailChildBillcode();
            mQueryLoadDetailChildBillcode.setFlag(1);
            mQueryLoadDetailChildBillcode.setChildWaybillNo(result);
            childList.add(mQueryLoadDetailChildBillcode);
            mQueryLoadDetailBillcode.setBigTicket(true);
        } else {
            if (data != null) {
                for (int i = 0; i < data.getQuantity(); i++) {
                    String childWaybillNo = data.getWaybillNo() + String.format("%03d", i + 1);
                    QueryLoadDetailChildBillcode mQueryLoadDetailChildBillcode = new QueryLoadDetailChildBillcode();
                    if (result.equals(childWaybillNo)) {
                        mQueryLoadDetailChildBillcode.setFlag(1);
                    } else {
                        mQueryLoadDetailChildBillcode.setFlag(0);
                    }
                    mQueryLoadDetailChildBillcode.setChildWaybillNo(childWaybillNo);
                    childList.add(mQueryLoadDetailChildBillcode);
                }
            } else {
                QueryLoadDetailChildBillcode mQueryLoadDetailChildBillcode = new QueryLoadDetailChildBillcode();
                mQueryLoadDetailChildBillcode.setFlag(1);
                mQueryLoadDetailChildBillcode.setChildWaybillNo(result);
                childList.add(mQueryLoadDetailChildBillcode);
            }
        }
        mQueryLoadDetailBillcode.setChildList(childList);

        int goodsPriority = 0;
        if (mQueryLoadDetailBillcode.getGoodsPriority() != null) {
            goodsPriority = Integer.parseInt(mQueryLoadDetailBillcode.getGoodsPriority());
        }
        //插入表
        UnloadScanTable mUnloadScanTable = new UnloadScanTable(mQueryLoadDetailBillcode.getTask(), mQueryLoadDetailBillcode.getWaybillNo(), result,
                mQueryLoadDetailBillcode.getPackageNo(), mQueryLoadDetailBillcode.getStowageNo(), operTypeCode, inputType, "2",
                mQueryLoadDetailBillcode.getAreaCode(), SharedPreferUtil.getInstance().getValue(Common.USER_CODE),
                SharedPreferUtil.getInstance().getValue(Common.USER_NAME), Constants.GetSysTime(), Constants.GetScanTime(),
                SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE), SysInfo.getInstance().getImei(), mQueryLoadDetailBillcode.getCarNo(), 0,
                //waybillType：1-快运，2-快递
                goodsPriority, mQueryLoadDetailBillcode.getProductType(), joinWrokNum, joinUserName, deptType, null, platformNo,
                null, 1, mQueryLoadDetailBillcode.getCarMark(), null, null);
        mUnloadScanTable.setRelationDeptCode(mQueryLoadDetailBillcode.getRelationDeptCode());
        mUnloadScanTable.setRelationDeptName(mQueryLoadDetailBillcode.getRelationDeptName());
        mUnloadScanTable.setRelationDeptType(mQueryLoadDetailBillcode.getRelationDeptType());
        mUnloadScanTable.setSrcPiecesNum(mQueryLoadDetailBillcode.getSrcPiecesNum());
        Map<String, Object> map = new HashMap<>(2);
        map.put(FINAL_UNLOAD_SCAN_TABLE, mUnloadScanTable);
        map.put(FINAL_LOAD_INFO, mQueryLoadDetailBillcode);
        return map;
    }

    /**
     * 是否在上传数据
     */
    private boolean isDoing = false;
    private List<UnloadScanTable> mTempUnloadScanTableList;
    /**
     * 异常运单处理标志
     */
    private boolean exceptionWBHandle = false;
    private List<UnloadScanTable> uploadList;

    /**
     * 每次扫描未上传数据
     */
    private synchronized void upload(List<UnloadScanTable> list) {
        if (list == null) {
            list = new ArrayList<>();
            if (carPlanTaskEntityList != null) {
                for (CarPlanTaskEntity entity : carPlanTaskEntityList) {
                    //查询未上传数据
                    if (entity.getLoadTasks() != null) {
                        for (LoadBillTaskEntity loadTask : entity.getLoadTasks()) {
                            List<UnloadScanTable> unloadScanTables = mUnloadScanTableDao.getUnUpload(loadTask.getStowageNo(), operTypeCode);
                            if (unloadScanTables != null) {
                                list.addAll(unloadScanTables);
                            }
                        }
                    }
                }
            }
        }
        if (list.size() > 0) {
            //取list中前10条数据
            uploadList = list;
            if (list.size() >= Common.SCAN_UPLOAD_NUM) {
                list = list.subList(0, Common.SCAN_UPLOAD_NUM);
            }

            for (UnloadScanTable item : list) {
                item.setIsUpload(1);
            }
            //实例化上传类
            ScanLoadUploadRequest mScanLoadUploadRequest = new ScanLoadUploadRequest();
            mScanLoadUploadRequest.setRecords(list);
            isDoing = true;

            final List<UnloadScanTable> finalList = list;
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(QueryUnloadDetailResponse.class)
                    .setUrl(Constants.UPLOAD_DATA_POST_URL)
                    .setRequestObject(mScanLoadUploadRequest)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            isDoing = false;
                            if (isClickFlash || isClickSubmit) {
                                isClickFlash = false;
                                isClickSubmit = false;
                                dismissPgDlg();
                                setScannerEnabled(true);
                                SoundVibratorManager.playSound(2);
                                showToast(msg);
                            }
                        }

                        @Override
                        public void onError(final String msg, final Object obj) {
                            isDoing = false;
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        setScannerEnabled(true);
                                        if (finalList.size() == 1) {
                                            if (isClickSubmit) {
                                                LoadUtil.updateErrorWaybillStatus(finalList, mUnloadScanTableDao);
                                                upload(null);
                                            } else if (!msg.equals(Constants.PLEASE_CHECK_NET)) {
                                                showError2(msg, finalList);
                                            }
                                        } else if (finalList.size() > 1) {
                                            if (exceptionWBHandle && msg.contains("运单已签收不能装车")) {
                                                if (isClickSubmit) {
                                                    LoadUtil.updateErrorWaybillStatus(finalList, mUnloadScanTableDao);
                                                    upload(null);
                                                } else if (!msg.equals(Constants.PLEASE_CHECK_NET)) {
                                                    showError2(msg, finalList);
                                                }
                                            } else {
                                                //运单上传失败后，遍历list单个上传，找出有异常的运单提示用户删除后，后面的运单批量上传
                                                exceptionWBHandle = true;
                                                mTempUnloadScanTableList = finalList;
                                                List<UnloadScanTable> tempList = new ArrayList<>();
                                                if (msg.contains("运单已签收不能装车")) {
                                                    String waybillNo = finalList.get(0).getWaybillNo();
                                                    for (UnloadScanTable item : finalList) {
                                                        if (waybillNo.equals(item.getWaybillNo())) {
                                                            tempList.add(item);
                                                        }
                                                    }
                                                } else {
                                                    tempList.add(finalList.get(0));
                                                }
                                                upload(tempList);
                                            }
                                        } else {
                                            if (isClickSubmit) {
                                                LoadUtil.updateErrorWaybillStatus(finalList, mUnloadScanTableDao);
                                                upload(null);
                                            } else if (!msg.equals(Constants.PLEASE_CHECK_NET)) {
                                                //显示错误信息
                                                showError(msg, finalList);
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            isDoing = false;
                            if (obj instanceof QueryUnloadDetailResponse) {
                                try {
                                    //更新数据库状态
                                    for (UnloadScanTable item : finalList) {
                                        mUnloadScanTableDao.update(item);
                                    }
                                    //减少未上传数据
                                    decreaseUnloadCount(finalList.size());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                if (exceptionWBHandle) {
                                    //遍历异常运单中的正常运单
                                    Iterator<UnloadScanTable> it = mTempUnloadScanTableList.iterator();
                                    while (it.hasNext()) {
                                        UnloadScanTable item = it.next();
                                        for (UnloadScanTable unloadScanTable : finalList) {
                                            if (item.getWaybillNo().equals(unloadScanTable.getWaybillNo())) {
                                                it.remove();
                                                break;
                                            }
                                        }
                                    }
                                    if (mTempUnloadScanTableList.size() > 0) {
                                        List<UnloadScanTable> list = new ArrayList<>();
                                        list.add(mTempUnloadScanTableList.get(0));
                                        upload(list);
                                    }
                                } else {
                                    synchronized (uploadList) {
                                        Iterator<UnloadScanTable> it = uploadList.iterator();
                                        int count = 0;
                                        while (it.hasNext()) {
                                            it.next();
                                            if (count < Common.SCAN_UPLOAD_NUM) {
                                                it.remove();
                                            }
                                            count++;
                                        }
                                        upload(uploadList);
                                        return;
                                    }
                                }
                            }

                            if (isClickFlash) {
                                isClickFlash = false;
                                loadData(false);
                            }
                            if (isClickSubmit) {
                                isClickSubmit = false;
                                uploadTask();
                            }
                        }
                    });
        } else {
            isDoing = false;
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    LoadUtil.setUnloadCount(num, carPlanTaskEntityList, mUnloadScanTableDao, operTypeCode);
                    if (isClickFlash) {
                        isClickFlash = false;
                        loadData(false);
                    }
                    if (isClickSubmit) {
                        isClickSubmit = false;
                        uploadTask();
                    }
                }
            });
        }
    }

    /**
     * 显示错误信息
     */
    private void showError(String error, final List<UnloadScanTable> list) {
        setScannerEnabled(false);
        if (error.contains("装车任务已完成")) {
            MyDialog dialog = new MyDialog(this);
            dialog.setIcon(R.drawable.alert);
            dialog.setMessage(error);
            dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        mUnloadScanTableDao.delete(list);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    setScannerEnabled(true);
                    finish();
                }
            });
            dialog.setCancelable(false);
            dialog.show();
        } else {
            isDoing = false;
            setScannerEnabled(true);
        }
    }

    /**
     * 显示错误信息
     */
    private void showError2(String error, final List<UnloadScanTable> list) {
        setScannerEnabled(false);
        if (isFinishing()) {
            return;
        }
        MyDialog dialog = MyDialog.getInstance(this);
        dialog.setIcon(R.drawable.alert);
        boolean showNo;
        String btnStr;
        String msg;

        if (error.contains("9601")) {
            String errorWaybill = error.substring(error.indexOf("[") + 1, error.indexOf("]"));
            error = "同行交接时，没有交接此子单号：" + errorWaybill;
            msg = error + "，是否放弃该条码扫描？";
            showNo = true;
            btnStr = "是";
        } else if (error.contains("车辆配载重量已超过该车型额定重量，禁止装车！")) {
            showNo = false;
            btnStr = "好的";
            msg = "上传报错:【" + error + "】，请否放弃该条码扫描？";
        } else {
            showNo = true;
            btnStr = "是";
            msg = "上传报错:【" + error + "】，是否放弃该条码扫描？";
        }

        dialog.setMessage(msg);
        dialog.setPositiveClickListener(btnStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setScannerEnabled(true);
                dialog.dismiss();
                MyDialog.setNull();
                isDoing = false;
                try {
                    mUnloadScanTableDao.delete(list);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                //设置内存中的数据为未扫描
                for (UnloadScanTable item : list) {
                    //遍历服务器返回数据集合
                    for (LoadInfo billDto : loadInfos) {
                        if (item.getWaybillNo().equals(billDto.getWaybillNo())) {
                            if (billDto.getChildList() != null) {
                                Iterator<QueryLoadDetailChildBillcode> it = billDto.getChildList().iterator();
                                while (it.hasNext()) {
                                    QueryLoadDetailChildBillcode child = it.next();
                                    if (child.getChildWaybillNo().equals(item.getChildWaybillNo())) {
                                        it.remove();
                                    }
                                }
                                break;
                            }
                            billDto.setWaybillType(1);
                        }
                    }
                }
                //根据复选框类型显示运单列表
                showInfosByCheckBox();
                //处理异常运单
                if (exceptionWBHandle) {
                    exceptionWBHandle = false;
                    //内存中删除异常的运单
                    mTempUnloadScanTableList.removeAll(list);
                    upload(null);
                }
            }
        });
        dialog.setCancelable(false);

        if (showNo) {
            dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyDialog.setNull();
                    dialog.dismiss();
                    isDoing = false;
                    setScannerEnabled(true);
                }
            });
        }

        dialog.setCanceledOnTouchOutside(false);
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private synchronized void setUnloadCount(String count) {
        //设置未上传数
        num.setText(count);
    }

    private int getUnloadCount() {
        return Integer.parseInt(num.getText().toString());
    }

    private synchronized void addUnloadCount() {
        //设置未上传数
        num.setText((Integer.parseInt(num.getText().toString()) + 1) + "");
    }

    private synchronized void decreaseUnloadCount(int decreaseCount) {
        //更新未上传数
        int count = Integer.parseInt(num.getText().toString()) - decreaseCount;
        if (count < 0) {
            num.setText("0");
            count = 0;
        } else {
            num.setText(count + "");
        }
        EventBus.getDefault().post(new CountEvent(count));
    }

    public LoadScanActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_scan);
        setHandler();
        initView();
        initValue();
        //注册事件
        EventBus.getDefault().register(this);

        ThreadPoolUtils.execute(new UploadRunnable());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            switch (v.getId()) {
                case R.id.load_task_listview:
                    listview.requestDisallowInterceptTouchEvent(true);
                    break;
                default:
                    mScrollView.requestDisallowInterceptTouchEvent(true);
                    break;
            }
        }
        return false;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!cbKuaiYun.isChecked() && !cbKuaiDi.isChecked()) {
            showToast("至少保留一项！");
            buttonView.setChecked(true);
            return;
        }
        //根据复选框类型显示运单列表
        showInfosByCheckBox();
    }

    /**
     * 根据复选框类型显示运单列表
     */
    private void showInfosByCheckBox() {
        if (cbKuaiYun.isChecked() && cbKuaiDi.isChecked()) {
            //显示所有运单
            showInfosByType(0);
        } else if (cbKuaiYun.isChecked()) {
            //显示快运运单
            showInfosByType(1);
        } else {
            //显示快递运单
            showInfosByType(2);
        }
    }

    /**
     * 根据type显示快运或者快递的运单
     *
     * @param type 0-所有，1-快运，2-快递
     */
    private void showInfosByType(int type) {
        if (loadInfos != null) {
            if (type == 0) {
                loadListAdapter(loadInfos);
                return;
            }
            List<LoadInfo> tempInfo = new ArrayList<>();
            for (LoadInfo item : loadInfos) {
                if (type == 1 && !UcWaybillValidate.validate(item.getWaybillNo())) {
                    //快运运单
                    tempInfo.add(item);
                } else if (type == 2 && UcWaybillValidate.validate(item.getWaybillNo())) {
                    //快递运单
                    tempInfo.add(item);
                }
            }
            loadListAdapter(tempInfo);
        }
    }

    /**
     * 加载list适配器
     *
     * @param list 运单列表集合
     */
    private void loadListAdapter(List<LoadInfo> list) {
        loadAdapter(list);
        //更新汇总数据
        collectData(list);
    }

    private void loadAdapter(List<LoadInfo> list) {
        if (adapter == null) {
            adapter = new LoadScanAdapter(LoadScanActivity.this, list);
            listview.setAdapter(adapter);
        } else {
            adapter.setDataList(list);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 异步排序
     */
    private void asyncSort(final List<LoadInfo> list) {
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                sortList(list);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                loadAdapter(list);
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 上传数据的线程
     */
    private class UploadRunnable implements Runnable {
        @Override
        public void run() {
            while (!isExit) {
                //是否正在上传数据
                if (!isDoing) {
                    //上传数据
                    upload(null);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//
        if (mTimer != null) {
            mTimer.cancel();
        }
        //停止刷新
        if (checkTimeHandler != null) {
            checkTimeHandler.removeCallbacks(runnable);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取装卸组信息
        getGroupInfo();
        // 第一次进入上传后加载数据，后面直接刷新数据
        if (isfirst) {
            loadData(false);
        }
        isfirst = false;
        //获取发车时间开始倒计时
        getTimeStartTime();
        // 间隔300秒(五分钟),自动校验时间
        checkTimeHandler.postDelayed(runnable, loadTime);
    }

    private int zpiao = 0;
    private int zjian = 0;
    private int spiao = 0;
    private int sjian = 0;
    private double zweight = 0.0;
    private double zvolume = 0.0;
    private double sweight = 0.0;
    private double svolume = 0.0;
    private double chargedWeight = 0.0;
    //卡航总重量
    private double kaTotalWeight = 0;
    //卡航总体积
    private double kaTotalVolume = 0;
    //卡航实操重量
    private double kaShiWeight = 0;
    //卡航实操体积
    private double kaShiVolume = 0;

    //更新汇总数据
    private void collectData(final List<LoadInfo> list) {

        zpiao = 0;
        zjian = 0;
        spiao = 0;
        sjian = 0;
        zweight = 0.0;
        zvolume = 0.0;
        sweight = 0.0;
        svolume = 0.0;
        chargedWeight = 0.0;
        sfweight = 0.0;
        //卡航总重量
        kaTotalWeight = 0;
        //卡航总体积
        kaTotalVolume = 0;
        //卡航实操重量
        kaShiWeight = 0;
        //卡航实操体积
        kaShiVolume = 0;

        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                // 遍历下拉下来的每个运单
                for (LoadInfo billDto : list) {
                    //遍历服务器返回数据集合
                    zpiao += 1;
                    if (billDto.getSrcPiecesNum() == null) {
                        billDto.setSrcPiecesNum(0);
                    } else if (billDto.getWaybillType() != null && billDto.getWaybillType() == 2) {
                        zjian++;
                    } else {
                        zjian += billDto.getSrcPiecesNum();
                    }

                    if (billDto.getPiecesNum() == null) {
                        billDto.setPiecesNum(0);
                    }
                    if (billDto.getWeight() == null) {
                        billDto.setWeight(new BigDecimal(0));
                    } else {
                        zweight = BigDecimalUtils.add(billDto.getWeight().doubleValue(), zweight);
                    }

                    if (billDto.getVolume() == null) {
                        billDto.setVolume(new BigDecimal(0));
                    } else {
                        zvolume = BigDecimalUtils.add(billDto.getVolume().doubleValue(), zvolume);
                    }

                    if (billDto.getChargedWeight() == null) {
                        billDto.setChargedWeight(new BigDecimal(0));
                    }

                    int count = billDto.getScanCount();
                    //统计已扫描的数量
                    if (count > 0) {
                        if ((billDto.getWaybillNo() + "000").equals(billDto.getChildList().get(0).getChildWaybillNo())) {
                            //大票货
                            spiao += 1;
                            sjian += count;
                            sweight += BigDecimalUtils.round(billDto.getWeight().doubleValue(), 4);
                            svolume += BigDecimalUtils.round(billDto.getVolume().doubleValue(), 4);
                            sfweight += BigDecimalUtils.round(billDto.getChargedWeight().doubleValue(), 4);
                        } else if ("2".equals(billDto.getKyWaybillType())) {
                            //整车单
                            spiao += 1;
                            sjian += billDto.getSrcPiecesNum();
                            sweight += BigDecimalUtils.round(billDto.getWeight().doubleValue(), 4);
                            svolume += BigDecimalUtils.round(billDto.getVolume().doubleValue(), 4);
                            sfweight += BigDecimalUtils.round(billDto.getChargedWeight().doubleValue(), 4);
                        } else {
                            //普通货
                            spiao += 1;
                            sjian += count;
                            sweight += BigDecimalUtils.mul(BigDecimalUtils.div(billDto.getWeight().doubleValue(), billDto.getSrcPiecesNum(), 4), count);
                            svolume += BigDecimalUtils.mul(BigDecimalUtils.div(billDto.getVolume().doubleValue(), billDto.getSrcPiecesNum(), 4), count);
                            sfweight += BigDecimalUtils.mul(BigDecimalUtils.div(billDto.getChargedWeight().doubleValue(), billDto.getSrcPiecesNum(), 4), count);
                        }
                    } else if (billDto.getWaybillType() != null && billDto.getWaybillType() == 2) {
                        spiao++;
                        sjian++;
                    }
                    double childOneWeight = 0;
                    if (billDto.getChildList() != null) {
                        //统计已扫描的计费重量
                        childOneWeight = billDto.getChargedWeight().doubleValue() / billDto.getChildList().size();
                    }
                    //当前运单已扫计费重量
                    chargedWeight += childOneWeight * count;
                    //统计卡航数据
                    if ("CP24".equals(billDto.getProductType()) || "CP13".equals(billDto.getProductType())) {
                        kaTotalWeight += billDto.getWeight().doubleValue();
                        kaTotalVolume += billDto.getVolume().doubleValue();
                        kaShiWeight += BigDecimalUtils.mul(BigDecimalUtils.div(billDto.getWeight().doubleValue(), billDto.getSrcPiecesNum(), 4), count);
                        kaShiVolume += BigDecimalUtils.mul(BigDecimalUtils.div(billDto.getVolume().doubleValue(), billDto.getSrcPiecesNum(), 4), count);
                    }
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                //装载率
                double loadLimit = chargedWeight / mLoadLimit;
                if (Double.isNaN(loadLimit) || Double.isInfinite(loadLimit)) {
                    tvLoadLimit.setText("0%");
                } else {
                    DecimalFormat df = new java.text.DecimalFormat("#.##");
                    tvLoadLimit.setText(df.format(loadLimit * 100) + "%");
                }

                //设置总重，体积，票数
                totle_weight.setText(BigDecimalUtils.round(zweight, 2) + "");
                totle_volume.setText(BigDecimalUtils.round(zvolume, 2) + "");
                totle_piao.setText(zpiao + "");
                totle_jian.setText(zjian + "");
                mRealWeight = sweight;
                hold_weight.setText(BigDecimalUtils.round(sweight, 2) + "");
                hold_volume.setText(BigDecimalUtils.round(svolume, 2) + "");
                hold_piao.setText(spiao + "");
                hold_jian.setText(sjian + "");

                //设置未上传数
                setUnloadCount(mUnloadScanTableDao.queryCount("isUpload", 0, 1) + "");
                //统计卡航数据
                DecimalFormat df = new java.text.DecimalFormat("#.##");
                tvKaTotalWeight.setText(String.format("%s", df.format(kaTotalWeight)));
                tvKaTotalVolume.setText(String.format("%s", df.format(kaTotalVolume)));
                tvKaShiWeight.setText(String.format("%s", df.format(kaShiWeight)));
                tvKaShiVolume.setText(String.format("%s", df.format(kaShiVolume)));

                asyncSort(list);
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 统计卡航数据
     */
    private void collectKaHangData() {
        //卡航总重量
        double kaTotalWeight = 0;
        //卡航总体积
        double kaTotalVolume = 0;
        //卡航实操重量
        double kaShiWeight = 0;
        //卡航实操体积
        double kaShiVolume = 0;
        for (LoadInfo loadInfo : loadInfos) {
            if ("CP24".equals(loadInfo.getProductType()) || "CP13".equals(loadInfo.getProductType())) {
                int count = loadInfo.getScanCount();
                kaTotalWeight += loadInfo.getWeight().doubleValue();
                kaTotalVolume += loadInfo.getVolume().doubleValue();
                kaShiWeight += BigDecimalUtils.mul(BigDecimalUtils.div(loadInfo.getWeight().doubleValue(), loadInfo.getSrcPiecesNum(), 4), count);
                kaShiVolume += BigDecimalUtils.mul(BigDecimalUtils.div(loadInfo.getVolume().doubleValue(), loadInfo.getSrcPiecesNum(), 4), count);
            }
        }
        DecimalFormat df = new java.text.DecimalFormat("#.##");
        tvKaTotalWeight.setText(String.format("%s", df.format(kaTotalWeight)));
        tvKaTotalVolume.setText(String.format("%s", df.format(kaTotalVolume)));
        tvKaShiWeight.setText(String.format("%s", df.format(kaShiWeight)));
        tvKaShiVolume.setText(String.format("%s", df.format(kaShiVolume)));
    }

    @Override
    protected void onDestroy() {
        //停止刷新
        if (checkTimeHandler != null) {
            checkTimeHandler.removeCallbacks(runnable);
        }
        if (mTimer != null) {
            mTimer.cancel();
        }

        if (loadInfos != null) {
            loadInfos.clear();
        }
        //退出上传
        isExit = true;
        //取消注册事件
        EventBus.getDefault().unregister(this);
        flashHandler.removeCallbacks(falshRunnable);
        super.onDestroy();
    }

    @Override
    public String getPageName() {
        return "装车扫描";
    }

    public void initView() {
        ((TextView) findViewById(R.id.title)).setText("装车扫描");

        findViewById(R.id.load_scan_back).setOnClickListener(this);
        flashBtn = findViewById(R.id.load_scan_refresh_btn);
        flashBtn.setOnClickListener(this);
        findViewById(R.id.load_upload).setOnClickListener(this);
        // 手动添加
        btnAdd = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(this);
        // 撤销装车
        findViewById(R.id.btn_del).setOnClickListener(this);
        totle_weight = findViewById(R.id.totle_weight);
        totle_volume = findViewById(R.id.totle_volume);
        totle_piao = findViewById(R.id.totle_piao);
        totle_jian = findViewById(R.id.totle_jian);
        hold_weight = findViewById(R.id.hold_weight);
        hold_volume = findViewById(R.id.hold_volume);
        hold_piao = findViewById(R.id.hold_piao);
        hold_jian = findViewById(R.id.hold_jian);
        // 未上传数据显示
        num = findViewById(R.id.num);
        next_station = findViewById(R.id.next_station);
        next_station.setOnClickListener(this);

        listview = findViewById(R.id.load_task_listview);
        listview.setOnTouchListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            listview.setNestedScrollingEnabled(true);
        }
        mScrollView = findViewById(R.id.load_scan_scrollView);
        mScrollView.setOnTouchListener(this);
        btnLoadUnloadGroup = findViewById(R.id.btn_modifyLoadUnloadPeople);
        btnLoadUnloadGroup.setOnClickListener(this);
        tvShowDesc = findViewById(R.id.tv_showDesc);
        //要隐藏和显示的布局
        llFunctionBtn = findViewById(R.id.ll_function_btn);
        llFunctionBtn.setVisibility(View.GONE);
        //向下按钮
        ivDownLayout = findViewById(R.id.iv_down_layout);
        ivDownLayout.setOnClickListener(this);
        tvloadTime = findViewById(R.id.tv_loadTime);
        tvLoadLimit = findViewById(R.id.tv_loadLimit);
        tvKaTotalWeight = findViewById(R.id.ka_total_weight);
        tvKaTotalVolume = findViewById(R.id.ka_total_volume);
        tvKaShiWeight = findViewById(R.id.ka_hold_weight);
        tvKaShiVolume = findViewById(R.id.ka_hold_volume);
        cbKuaiYun = findViewById(R.id.cb_kuai_yun);
        cbKuaiYun.setOnCheckedChangeListener(this);
        cbKuaiDi = findViewById(R.id.cb_kuai_di);
        cbKuaiDi.setOnCheckedChangeListener(this);
    }


    int kuaidiMerge = 0; //0代表不是快递合并装车 1代表快递合并装车

    public void initValue() {
        //对话框初始化
        MyDialog.setNull();
        //新手引导提示
        Common.showIntro(this, ivDownLayout, "点击可显示隐藏功能", this.getPageName());
        cbKuaiYun.setChecked(true);
        cbKuaiDi.setChecked(true);
        //设置不加载任务标志
        sharedPreferUtil.setBooleanValue(Common.SUCCESS_SUBMIT_LOAD, false);
        mDepartmentTableDao = new DepartmentTableDao();
        mJieLiuJianTableDao = new JieLiuJianTableDao();
        mBillRouteDao = new BillRouteTableDao();
        loadInfos = new ArrayList<>();
        Bundle bundle = getIntent().getExtras();
        carPlanTaskEntityList = (List<CarPlanTaskEntity>) bundle.getSerializable("carPlaneTasks");
        mJoinPeopleEntityList = (List<JoinPeopleEntity>) bundle.getSerializable("joinPeopleList");
        task = getIntent().getStringExtra("task");
        kuaidiMerge = getIntent().getIntExtra("isKuaidiMerge", 0);
        //初始任务设置
        setInitTask();
        //获取装卸组信息
        getGroupInfo();

        //查询数据字典车型校验开关
        queryDictCarModelSwitch();
        //查询上传扫描条数
        Common.queryDictScanUploadNum();
        //数据字典查询：分拨装车重量改小差值
        queryDictWeightChange();
        //数据字典查询：快递错分开关
        queryUcCuoFenSwitch();
        //数据字典，查询融合装车扫描创建任务开关
        Common.queryMergeLoadScanCreateTask();
    }

    /**
     * 初始任务设置
     */
    private void setInitTask() {
        StringBuilder tempNextStation = new StringBuilder();
        isYmOneTask = true;
        isUcOneTask = true;
        if (carPlanTaskEntityList != null) {
            for (CarPlanTaskEntity taskEntity : carPlanTaskEntityList) {
                if (taskEntity.getLoadTasks() != null) {
                    for (LoadBillTaskEntity loadTask : taskEntity.getLoadTasks()) {
                        if (loadTask.isCheck()) {
                            if (loadTask.getDestDeptName() != null && !tempNextStation.toString().contains(loadTask.getDestDeptName())) {
                                tempNextStation.append(loadTask.getDestDeptName() + " ");
                            }
                            if (loadTask.getStowageNo().startsWith("P")) {
                                isUcOneTask = false;
                            } else {
                                isYmOneTask = false;
                            }
                        }
                    }
                } else {
                    for (VehTaskNodeEntity node : taskEntity.getNodes()) {
                        if (node.isSelected()) {
                            tempNextStation.append(node.getTaskNodeName() + " ");
                        }
                    }
                }
            }


            if (carPlanTaskEntityList.get(0).getTaskType() == 1) {
                isKuaYueTask = true;
            } else {
                isKuaYueTask = false;
            }
            for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
                if (planTask.getLoadTasks() != null) {
                    for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                        if (loadTask.isCheck()) {
                            if (loadTask.getStowageNo().startsWith("P")) {
                                //取快运装车第一个任务
                                if (mYmLoadTask == null) {
                                    mYmLoadTask = loadTask;
                                }
                            } else {
                                //取快递装车第一个任务
                                if (mUcLoadTask == null) {
                                    mUcLoadTask = loadTask;
                                }
                            }
                        }
                    }
                }
            }
        }

        //设置下一站
        next_station.setText(tempNextStation.toString());

        //快运
        //设置任务号默认取第一个
        if (mYmLoadTask != null) {
            carCode = mYmLoadTask.getStowageNo();
            carNo = mYmLoadTask.getCarNo();
            currentStation = mYmLoadTask.getSrcDeptName();
            currentStationCode = mYmLoadTask.getSrcDeptCode();
            nextStation = mYmLoadTask.getDestDeptName();
            nextStationCode = mYmLoadTask.getDestDeptCode();
        }
    }

    /**
     * 数据字典查询：快递错分开关(uc_cuofen_switch)
     */
    private void queryUcCuoFenSwitch() {
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "uc_cuofen_switch");
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        if (response != null && response.getData() != null) {
                            List<BaseDictEntity> list = response.getData();
                            if (!list.isEmpty()) {
                                String dictValue = list.get(0).getDictValue();
                                if ("1".equals(dictValue)) {
                                    //快递错分开关开启
                                    isUcCuoFenSwitch = true;
                                } else {
                                    isUcCuoFenSwitch = false;
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 数据字典查询：分拨装车运单重量改小差值（waybill_change_diff）
     */
    private void queryDictWeightChange() {
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "waybill_change_diff");
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        if (response != null && response.getData() != null) {
                            mDictWeightChangeDiffList = response.getData();
                            if (mDictWeightChangeDiffList != null && !mDictWeightChangeDiffList.isEmpty()) {
                                for (BaseDictEntity item : mDictWeightChangeDiffList) {
                                    if (item.getDictKey() == 1) {
                                        try {
                                            mWeightDiff = Double.parseDouble(item.getDictValue());
                                        } catch (NumberFormatException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 查询数据字典车型校验开关
     */
    private void queryDictCarModelSwitch() {
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "car_model_switch");
        //查询类型，1-只查询未作废的，为null则查询所有(包含作废和未作废的)
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        if (response != null && response.getData() != null) {
                            mDictSwitchList = response.getData();
                            if (mDictSwitchList != null && !mDictSwitchList.isEmpty()) {
                                //查询车型额定载重
                                queryCarModelLoad();
                            }
                        }
                    }
                });
    }

    /**
     * 查询车型额定载重
     */
    private void queryCarModelLoad() {
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "car_model");
        //查询类型，1-只查询未作废的，为null则查询所有(包含作废和未作废的)
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        if (response != null && response.getData() != null) {
                            mDictCarModelList = response.getData();
                        }

                        Observable.create(new Observable.OnSubscribe<Void>() {
                            @Override
                            public void call(Subscriber<? super Void> subscriber) {

                                if (carPlanTaskEntityList != null) {
                                    mLimitWeightStowage = new ArrayList<>();
                                    for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
                                        if (planTask.getLoadTasks() != null) {
                                            for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                                                //装车任务匹配车型
                                                String carModel = planTask.getCarModel().replace("米", "");

                                                //用于计算装载率
                                                for (BaseDictEntity carMod : mDictCarModelList) {
                                                    if (carMod.getDictValue().contains(carModel)) {
                                                        mLoadLimit += Integer.parseInt(carMod.getExternalParam3());
                                                    }
                                                }

                                                //只 支线校验车型
                                                if (loadTask.getBizTypeCode() == 2) {
                                                    //查询装车任务下一站网点信息
                                                    DepartmentTable nextDeptTable = new DepartmentTableDao().queryDeptByDeptCode(loadTask.getDestDeptCode());
                                                    if (mDictSwitchList != null && carModel != null) {
                                                        for (BaseDictEntity dictEntity : mDictSwitchList) {
                                                            if (dictEntity.getDictValue().contains(carModel)
                                                                    && "1".equals(dictEntity.getExternalParam1())) {
                                                                //匹配到开启限重校验的车型
                                                                if (mDictCarModelList != null) {
                                                                    //获取车型限重数据
                                                                    for (BaseDictEntity carMod : mDictCarModelList) {
                                                                        if (carMod.getDictValue().contains(carModel)) {
                                                                            CarModelLimitWeightEntity entity = new CarModelLimitWeightEntity();
                                                                            entity.setStowageNo(loadTask.getStowageNo());
                                                                            entity.setCarModel(carMod.getDictValue());
                                                                            entity.setLimitWeight(carMod.getExternalParam3());
                                                                            entity.setBizTypeCode(loadTask.getBizTypeCode());
                                                                            try {
                                                                                //限重倍数
                                                                                entity.setMultiple(Double.parseDouble(dictEntity.getExternalParam2()));
                                                                            } catch (Exception e) {
                                                                                e.printStackTrace();
                                                                                entity.setMultiple(1);
                                                                            }
                                                                            //当前是网点，下一站是分拨，则设置为始发网点
                                                                            if (nextDeptTable != null) {
                                                                                deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                                                                                if (deptType != 5 && deptType != 6
                                                                                        && (nextDeptTable.getDeptType() == 5
                                                                                        || nextDeptTable.getDeptType() == 6)) {
                                                                                    entity.setStartDept(true);
                                                                                }
                                                                            }
                                                                            mLimitWeightStowage.add(entity);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                subscriber.onCompleted();
                            }
                        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable throwable) {
                            }

                            @Override
                            public void onNext(Void aVoid) {
                            }
                        });
                    }
                });
    }

    /**
     * 获取装卸组信息
     */
    private void getGroupInfo() {
        Bundle bundle = getIntent().getExtras();
        //获取登录的部门类型
        deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (deptType == 5 || deptType == 6) {
            LoadUnLoadGroupTable loadUnLoadGroupTable = new LoadUnloadGroupTableDao().getData();
            if (loadUnLoadGroupTable != null) {
                platformNo = loadUnLoadGroupTable.getPlatform();
            }
            //登录分拨获取装卸组
            joinWrokNum = bundle.getString("joinWrokNum");
            joinUserName = bundle.getString("joinUserName");
            if (joinWrokNum == null || joinUserName != null) {
                if (loadUnLoadGroupTable != null) {
                    joinWrokNum = loadUnLoadGroupTable.getUserCodes();
                    joinUserName = loadUnLoadGroupTable.getUserNames();
                }
            }

            if ((joinWrokNum == null || joinWrokNum.equals("")) && ((joinUserName == null) || joinUserName.equals(""))) {
                joinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
                joinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
                if (joinUserName == null || joinUserName.equals("")) {
                    joinUserName = joinWrokNum;
                }
            } else if (joinUserName == null || joinUserName.equals("")) {
                joinUserName = joinWrokNum;
            }
            tvShowDesc.setVisibility(View.GONE);
            btnLoadUnloadGroup.setVisibility(View.VISIBLE);
        } else {
            joinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
            joinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
            if (joinUserName == null || joinUserName.equals("")) {
                joinUserName = joinWrokNum;
            }
            tvShowDesc.setVisibility(View.VISIBLE);
            btnLoadUnloadGroup.setVisibility(View.GONE);
        }
        //自动检测没有省区的工号，自动添加上去
        String compCode = sharedPreferUtil.getCompanyCode();
        if (compCode == null || "".equals(compCode)) {
            showToast("企业编码为空！");
        }
        String[] userCodes = joinWrokNum.split(",");
        for (int i = 0; i < userCodes.length; i++) {
            String userCode = userCodes[i];
            if (!userCode.contains("@")) {
                userCodes[i] = userCode + "@" + compCode;
            }
        }
        StringBuilder tempUserCodes = new StringBuilder();
        for (String userCode : userCodes) {
            tempUserCodes.append(userCode + ",");
        }
        joinWrokNum = tempUserCodes.substring(0, tempUserCodes.length() - 1);
    }

    /**
     * 获取发车时间开始倒计时
     */
    private void getTimeStartTime() {
        //获取最近发车时间
        Date tempDate = null;
        if (carPlanTaskEntityList != null) {
            for (CarPlanTaskEntity planTaskEntity : carPlanTaskEntityList) {
                Date date = DateHelper.getDateTime(planTaskEntity.getPlanStartTime());
                if (date == null) {
                    continue;
                }
                if (tempDate == null) {
                    tempDate = date;
                    continue;
                }
                if (date.getTime() < tempDate.getTime()) {
                    tempDate = date;
                }
            }
        }
        if (tempDate != null) {
            Date currentDate = new Date();
            long diffTime = tempDate.getTime() - currentDate.getTime();
            if (diffTime <= 0) {
                tvloadTime.setText("00:00");
                tvloadTime.setTextColor(getResources().getColor(R.color.red));
            } else {
                long days = diffTime / (1000 * 60 * 60 * 24);
                long hours = (diffTime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
                long minutes = (diffTime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
                long seconds = (diffTime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);
                //剩余分钟
                long remainMinutes = (days * 24 * 60) + (hours * 60) + minutes;
                //发车时间开始倒计时
                startCountDown(remainMinutes, (int) seconds);
            }
        }
    }

    /**
     * 发车时间开始倒计时
     */
    private void startCountDown(long minutes, int remainSecond) {
        isTimeScan = true;
        if (remainSecond == 0) {
            minutes--;
        }
        mMinutes = minutes;
        if (remainSecond != 0) {
            timeSS = remainSecond;
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mMinutes <= 0 && timeSS <= 0) {
                    mTimer.cancel();
                    Bundle bundle = new Bundle();
                    bundle.putString("mm", "00");
                    bundle.putString("ss", "00");
                    Message msg = new Message();
                    msg.setData(bundle);
                    msg.what = HANDLER_100;
                    handler.sendMessage(msg);
                    return;
                }
                if (timeSS <= 0) {
                    mMinutes--;
                    timeSS = 60;
                }
                timeSS--;
                //分钟
                long mm = mMinutes;
                //秒
                long ss = timeSS % 60;
                String mmStr = "";
                String ssStr = "";
                if (mm >= 0 && mm < 10) {
                    mmStr = "0" + mm;
                } else {
                    mmStr = mm + "";
                }
                if (ss >= 0 && ss < 10) {
                    ssStr = "0" + ss;
                } else {
                    ssStr = ss + "";
                }
                Bundle bundle = new Bundle();
                bundle.putString("mm", mmStr);
                bundle.putString("ss", ssStr);
                Message msg = new Message();
                msg.setData(bundle);
                msg.what = HANDLER_100;
                handler.sendMessage(msg);
            }
        }, 0, 1000);
    }

    /**
     * 获取装车数据
     */
    public void loadData(final boolean isAutoLoad) {
        if (!isAutoLoad) {
            showPgDlg("正在加载...");
        }
        if (loadInfos != null) {
            loadInfos.clear();
        }
        startQueryLoadDetial(0, isAutoLoad);
    }

    /**
     * 开始查询装车明细
     */
    private void startQueryLoadDetial(int planTaskIndex, boolean isAutoLoad) {
        if (planTaskIndex > carPlanTaskEntityList.size() - 1) {
            dismissPgDlg();
            if (isClickLoadData) {
                isClickLoadData = false;
                //开启10秒倒计时线程，控制刷新按钮
                flashCount = 10;
                flashHandler.postDelayed(falshRunnable, 0);
            }
            /**加载显示获取的数据*/
            insertData(isAutoLoad);
            return;
        }

        CarPlanTaskEntity planTask = carPlanTaskEntityList.get(planTaskIndex);
        queryLoadDetailByLoadTask(planTask, 0, planTaskIndex, isAutoLoad);
    }

    /**
     * 根据装车任务查询装车明细
     */
    private void queryLoadDetailByLoadTask(final CarPlanTaskEntity planTask, final int loadTaskIndex, final int planTaskIndex, final boolean isAutoLoad) {
        if (planTask.getLoadTasks() != null) {
            if (loadTaskIndex > planTask.getLoadTasks().size() - 1) {
                queryLoadDetailByNode(planTask, 0, planTaskIndex, isAutoLoad);
                return;
            }
        } else {
            queryLoadDetailByNode(planTask, 0, planTaskIndex, isAutoLoad);
            return;
        }
        LoadBillTaskEntity loadTask = planTask.getLoadTasks().get(loadTaskIndex);
        loadTask.setTaskNo(planTask.getTaskNo());
        if (loadTask.isCheck()) {
            QueryLoadDetailRequest request = new QueryLoadDetailRequest();
            request.setStowageNo(loadTask.getStowageNo());
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setObject1(loadTask)
                    .setResponsClazz(QueryLoadDetailResponse.class)
                    .setUrl(Constants.QUERY_LOADDATA)
                    .setRequestObject(request)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            dismissPgDlg();
                            SoundVibratorManager.playSound(2);
                            showToast("加载数据失败：" + msg);
                            loadInfos = new ArrayList<>();
                            //根据复选框类型显示运单列表
                            showInfosByCheckBox();
                        }

                        @Override
                        public void onSuccess(Object obj, Object obj1) {
                            QueryLoadDetailResponse response = (QueryLoadDetailResponse) obj;
                            LoadBillTaskEntity loadTask = (LoadBillTaskEntity) obj1;
                            //装车数据
                            List<QueryLoadDetailBillcode> loadDataEntityList = response.getData();
                            //查询网点类型
                            DepartmentTable departmentTable = mDepartmentTableDao.queryDeptByDeptCode(loadTask.getDestDeptCode());
                            if (departmentTable != null) {
                                loadTask.setRelationDeptType(departmentTable.getDeptType());
                            }

                            List<LoadInfo> tempLoadInfos = chanageList(loadDataEntityList, loadTask, null);
                            if (tempLoadInfos != null && tempLoadInfos.size() > 0) {
                                loadInfos.addAll(tempLoadInfos);
                            }
                            queryLoadDetailByLoadTask(planTask, loadTaskIndex + 1, planTaskIndex, isAutoLoad);
                        }

                        @Override
                        public void onSuccess(Object obj) {

                        }
                    });
        } else {
            queryLoadDetailByLoadTask(planTask, loadTaskIndex + 1, planTaskIndex, isAutoLoad);
        }
    }

    /**
     * 根据下一站查询装车明细
     */
    private void queryLoadDetailByNode(final CarPlanTaskEntity planTask, final int nodeIndex, final int planTaskIndex, final boolean isAutoLoad) {
        if (nodeIndex > planTask.getNodes().size() - 1) {
            startQueryLoadDetial(planTaskIndex + 1, isAutoLoad);
            return;
        }
        VehTaskNodeEntity node = planTask.getNodes().get(nodeIndex);
        node.setTaskNo(planTask.getTaskNo());
        if (node.isSelected()) {

            if (planTask.getLoadTasks() != null) {
                for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                    if (node.getTaskNodeCode().equals(loadTask.getDestDeptCode()) && loadTask.isCheck()) {
                        //下一站任务已经创建，继续循环获取下一站
                        queryLoadDetailByNode(planTask, nodeIndex + 1, planTaskIndex, isAutoLoad);
                        return;
                    }
                }
            }

            QueryLoadDetailRequest request = new QueryLoadDetailRequest();
            request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
            request.setDestDeptCode(node.getTaskNodeCode());
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setObject1(node)
                    .setResponsClazz(QueryLoadDetailResponse.class)
                    .setUrl(Constants.QUERY_LOADDATA)
                    .setRequestObject(request)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            dismissPgDlg();
                            SoundVibratorManager.playSound(2);
                            showToast("加载数据失败：" + msg);
                            loadInfos = new ArrayList<>();
                            //根据复选框类型显示运单列表
                            showInfosByCheckBox();
                        }

                        @Override
                        public void onSuccess(Object obj, Object obj1) {
                            QueryLoadDetailResponse response = (QueryLoadDetailResponse) obj;
                            VehTaskNodeEntity nodeEntity = (VehTaskNodeEntity) obj1;
                            //装车数据
                            List<QueryLoadDetailBillcode> loadDataEntityList = response.getData();
                            //查询网点类型
                            DepartmentTable departmentTable = mDepartmentTableDao.queryDeptByDeptCode(nodeEntity.getTaskNodeCode());
                            if (departmentTable != null) {
                                nodeEntity.setRelationDeptType(departmentTable.getDeptType());
                            }

                            List<LoadInfo> tempLoadInfos = chanageList(loadDataEntityList, null, nodeEntity);
                            if (tempLoadInfos != null && tempLoadInfos.size() > 0) {
                                loadInfos.addAll(tempLoadInfos);
                            }
                            queryLoadDetailByNode(planTask, nodeIndex + 1, planTaskIndex, isAutoLoad);
                        }

                        @Override
                        public void onSuccess(Object obj) {

                        }
                    });
        } else {
            queryLoadDetailByNode(planTask, nodeIndex + 1, planTaskIndex, isAutoLoad);
        }
    }

    private List<LoadInfo> chanageList(List<QueryLoadDetailBillcode> list, LoadBillTaskEntity loadTask, VehTaskNodeEntity nodeEntity) {
        List<LoadInfo> loadInfos = new ArrayList<>();
        for (QueryLoadDetailBillcode bean : list) {
            LoadInfo loadInfo = new LoadInfo();
            if (loadTask != null) {
                loadInfo.setTask(loadTask.getStowageNo());
            }
            loadInfo.setWaybillNo(bean.getWaybillNo());
            loadInfo.setSrcPiecesNum(bean.getSrcPiecesNum());
            loadInfo.setPiecesNum(bean.getPiecesNum());
            loadInfo.setWeight(bean.getWeight());
            loadInfo.setVolume(bean.getVolume());
            loadInfo.setChargedWeight(bean.getChargedWeight());
            loadInfo.setWaybillRoute(bean.getWaybillRoute());
            loadInfo.setPackageNo(bean.getPackageNo());
            loadInfo.setAreaCode(bean.getAreaCode());
            loadInfo.setBillType(bean.getBillType());
            loadInfo.setStowageNo(bean.getStowageNo());
            loadInfo.setCarNo(bean.getCarNo());
            loadInfo.setRemark(bean.getRemark());
            loadInfo.setBigTicket(bean.isBigTicket());
            loadInfo.setGoodsPriority(bean.getGoodsPriority());
            loadInfo.setProductType(bean.getProductType());
            loadInfo.setChildList(bean.getChildList());
            loadInfo.setGetScanCount(bean.getScanCount());
            loadInfo.setDynamicRoute(bean.getDynamicRoute());
            if (loadTask != null) {
                loadInfo.setCarMark(loadTask.getTaskNo());
            } else if (nodeEntity != null) {
                loadInfo.setCarMark(nodeEntity.getTaskNo());
            }
            loadInfo.setWeightRate(bean.getWeightRate());
            loadInfo.setVolumeRate(bean.getVolumeRate());
            loadInfo.setKyWaybillType(bean.getWaybillType());
            //设置下一站部门属性
            if (loadTask != null) {
                loadInfo.setRelationDeptCode(loadTask.getDestDeptCode());
                loadInfo.setRelationDeptName(loadTask.getDestDeptName());
                //设置下一站部门类型
                loadInfo.setRelationDeptType(loadTask.getRelationDeptType());
            } else {
                loadInfo.setRelationDeptCode(nodeEntity.getTaskNodeCode());
                loadInfo.setRelationDeptName(nodeEntity.getTaskNodeName());
                //设置下一站部门类型
                loadInfo.setRelationDeptType(nodeEntity.getRelationDeptType());
            }

            loadInfos.add(loadInfo);

            if (loadInfo.getScanedWaybillNo() != null) {
                int waybillType = Common.getWaybillType(loadInfo.getScanedWaybillNo());
                if (waybillType == 1) {
                    //快运
                    mYmScaned = true;
                } else if (waybillType == 2) {
                    //快递
                    mUcScaned = true;
                }
            }
        }
        return loadInfos;
    }

    /**
     * 合并相同运单号
     */
    private List<LoadInfo> merageTheSameWayBillNos(List<LoadInfo> dataList) {
        HashMap<String, String> waybillNos = new HashMap<>();
        for (LoadInfo entity : dataList) {
            waybillNos.put(entity.getWaybillNo(), entity.getWaybillNo());
        }

        final List<LoadInfo> mergeDataList = new ArrayList<>();
        for (Map.Entry<String, String> map : waybillNos.entrySet()) {
            LoadInfo queryLoadDetailBillcode = new LoadInfo();
            List<QueryLoadDetailChildBillcode> childBillcodes = new ArrayList<>();
            for (LoadInfo entity : dataList) {
                if (!TextUtils.isEmpty(map.getKey()) && map.getKey().equals(entity.getWaybillNo())) {
                    if (entity.getChildList() != null) {
                        for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                            //设置子单合并前对应的配载单号
                            childEntity.setStowageNo(entity.getStowageNo());
                        }
                        childBillcodes.addAll(entity.getChildList());
                    }
                    if (queryLoadDetailBillcode.getGoodsPriority() != null && Integer.parseInt(queryLoadDetailBillcode.getGoodsPriority()) != Common.GOODSP_RIORITY_DEFAULT) {
                        //设置必走货字段
                        entity.setGoodsPriority(queryLoadDetailBillcode.getGoodsPriority());
                    }
                    if (queryLoadDetailBillcode.getPiecesNum() > 0) {
                        //若果有交接件数则设置上去
                        entity.setPiecesNum(queryLoadDetailBillcode.getPiecesNum());
                    }
                    queryLoadDetailBillcode = entity;
                }
            }
            //去除重复子单
            for (int i = 0; i < childBillcodes.size() - 1; i++) {
                for (int j = childBillcodes.size() - 1; j > i; j--) {
                    if (childBillcodes.get(j).getChildWaybillNo().equals(childBillcodes.get(i).getChildWaybillNo())) {
                        int flag = childBillcodes.get(j).getFlag();
                        if (flag != 1) {
                            //删除未扫描的运单
                            childBillcodes.remove(j);
                        }
                    }
                }
            }
            queryLoadDetailBillcode.setChildList(childBillcodes);
            mergeDataList.add(queryLoadDetailBillcode);
        }
        return mergeDataList;
    }

    /**
     * 查询数据库缓存数据，如果数据库存在列表中的数据，就将数据整合到列表中
     */
    protected void insertData(final boolean isAutoLoad) {
        showPgDlg("本地数据处理中...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                if (loadInfos == null) {
                    loadInfos = new ArrayList<>();
                }
                /**合并相同运单号*/
                loadInfos = merageTheSameWayBillNos(loadInfos);
                /****去除重复子单****/
                for (LoadInfo detailBillcode : loadInfos) {
                    List<QueryLoadDetailChildBillcode> childBillcodes = detailBillcode.getChildList();
                    if (childBillcodes != null) {
                        //当子单数大于开单件数或者交接件数时，做子单去重处理
                        if (childBillcodes.size() > detailBillcode.getSrcPiecesNum() || childBillcodes.size() > detailBillcode.getPiecesNum()) {
                            //获取重复的子单
                            List<String> rmeoveChildWaybillNo = new ArrayList<>();
                            for (int i = 0; i < childBillcodes.size() - 1; i++) {
                                for (int j = childBillcodes.size() - 1; j > i; j--) {
                                    if (childBillcodes.get(j).getChildWaybillNo().equals(childBillcodes.get(i).getChildWaybillNo())) {
                                        rmeoveChildWaybillNo.add(childBillcodes.get(j).getChildWaybillNo());
                                    }
                                }
                            }
                            //去除flag为0的重复子单
                            Iterator<QueryLoadDetailChildBillcode> it = childBillcodes.iterator();
                            while (it.hasNext()) {
                                QueryLoadDetailChildBillcode childBillcode = it.next();
                                for (String str : rmeoveChildWaybillNo) {
                                    if (str.equals(childBillcode.getChildWaybillNo()) && childBillcode.getFlag() == 0) {
                                        it.remove();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                /****去除重复子单****/
                //查询数据库中该任务未上传的数据
                for (CarPlanTaskEntity taskEntity : carPlanTaskEntityList) {
                    if (taskEntity.getLoadTasks() != null) {
                        for (LoadBillTaskEntity loadTask : taskEntity.getLoadTasks()) {
                            List<UnloadScanTable> expressLoadingEntities = mUnloadScanTableDao.getTaskWaybillNoData(loadTask.getStowageNo(), 1);
                            if (expressLoadingEntities != null && expressLoadingEntities.size() > 0) {
                                for (UnloadScanTable expressLoadingEntity : expressLoadingEntities) {
                                    for (LoadInfo billDto : loadInfos) {
                                        if (billDto.getChildList() != null && billDto.getChildList().size() > 0) {
                                            //遍历下载的每个子单数据 ，查看是否已扫描
                                            for (QueryLoadDetailChildBillcode item : billDto.getChildList()) {
                                                if (item.getChildWaybillNo().equals(expressLoadingEntity.getChildWaybillNo())) {
                                                    billDto.setSrcPiecesNum(expressLoadingEntity.getSrcPiecesNum());
                                                    if (expressLoadingEntity.getGoodsPriority() != null && expressLoadingEntity.getGoodsPriority() == 2) {
                                                        //设置为串货
                                                        billDto.setGoodsPriority("2");
                                                    }
                                                    //本地存在的数据设置已扫描
                                                    item.setFlag(1);
                                                    //设置本地已扫描的配载单
                                                    item.setStowageNo(expressLoadingEntity.getStowageNo());
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // 识别大票货件数
                identifyBigTicket();
                //排序
                sortList(loadInfos);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                //根据复选框类型显示运单列表
                showInfosByCheckBox();
                if (!isAutoLoad) {
                    SoundVibratorManager.playSound(1);
                }
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(LoadScanActivity.this, UnloadCompareActivity.class);
                Bundle bundle = new Bundle();
                // 打包运单号跳转到对比界面，查看扫描信息
                //bundle.putSerializable("waybill",(QueryLoadDetailBillcode) loadDataEntityList.get(position));
                Common.mLoadInfo = loadInfos.get(position);
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                String waybill = loadInfos.get(position).getWaybillNo();
                Intent intent = new Intent(LoadScanActivity.this, DetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("waybill", waybill);
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivity(intent);
                return true;
            }
        });
    }

    /**
     * 数据排序
     * 一级排序 红>白>黄>绿,getType
     * 二级排序 必-时-跨-串-快递-空
     */
    private List<LoadInfo> sortList(List<LoadInfo> list) {
        for (LoadInfo info : list) {
            info.setFirstSort(info.getType());
            info.setSecondSort(Common.setSecondType(info.getProductType(), info.getGoodsPriority(), info.getWaybillNo()));
        }
        String[] sortNameArr = {"firstSort", "secondSort"};
        // true升序,false降序
        boolean[] isAscArr = {true, true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }

    private void identifyBigTicket() {
        if (loadInfos != null && !loadInfos.isEmpty()) {
            for (LoadInfo detailBillcode : loadInfos) {
                if (detailBillcode.getChildList() != null && !detailBillcode.getChildList().isEmpty()) {
                    String childWaybillNo = detailBillcode.getChildList().get(0).getChildWaybillNo();
                    if ("000".equals(childWaybillNo.replace(detailBillcode.getWaybillNo(), ""))) {
                        detailBillcode.setBigTicket(true);
                    }
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent;
        Bundle bundle;
        switch (v.getId()) {
            case R.id.btn_modifyLoadUnloadPeople:
                intent = new Intent(this, LoadUnloadGroupActivity.class);
                bundle = new Bundle();
                bundle.putSerializable("carPlaneTasks", (Serializable) carPlanTaskEntityList);
                //扫描类型：1-装车扫描，2-卸车扫描
                bundle.putInt("scanType", Common.SCAN_TYPE_MERGE_LOAD);
                //装车类型：1-装车，2-卸车
                bundle.putInt("loadType", 1);
                bundle.putString("task", task);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.load_scan_back:
                activityBack();
                break;
            case R.id.load_scan_refresh_btn:
                clickFlashBtn();
                break;
            case R.id.load_upload:
                //上传数据，并完成任务
                submitMethod();
                break;
            case R.id.btn_add:

                intent = new Intent(LoadScanActivity.this, AddBillcodeActivity.class);
                bundle = new Bundle();
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_del:
                intent = new Intent(LoadScanActivity.this, BackoutActivity.class);
                bundle = new Bundle();
                bundle.putString("task", task);
                bundle.putInt("operTypeCode", operTypeCode);
                bundle.putInt("deptType", deptType);
                intent.putExtras(bundle);
                startActivityForResult(intent, 0);
                break;
            case R.id.iv_down_layout:
                //隐藏/显示布局
                HiddenAnimUtils.newInstance(this, llFunctionBtn, ivDownLayout, 50).toggle();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            activityBack();
        }
        return false;
    }

    private void activityBack() {
        String carNo = "";
        List<String> stowageNos = new ArrayList<>();
        for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
            carNo = planTask.getVehNo();
            if (planTask.getLoadTasks() != null) {
                for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                    stowageNos.add(loadTask.getStowageNo());
                }
            }
        }
        CreateStowagesEvent event = new CreateStowagesEvent();
        event.setCarNo(carNo);
        event.setStowageNos(stowageNos);
        event.setFromActivity(1);
        EventBus.getDefault().post(event);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == BACK_OUT_RESULT) {
            //装车撤销返回后，重新加载数据，保证数据同步
            loadData(false);
        }
    }

    /**
     * 点击刷新按钮，先触发上传后拉取装车扫描数据
     */
    private void clickFlashBtn() {
//        showPgDlg("正在加载...");
        isClickFlash = true;
        isClickLoadData = true;
        loadInfos.clear();
        upload(null);
    }

    private void submitMethod() {
        if (loadInfos == null || loadInfos.size() == 0) {
            showToast(getString(R.string.tmp_no_data));
            return;
        }
        //查询是否有扫描的单号
        if (!isLoadScan(loadInfos)) {
            SoundVibratorManager.playSound(2);
            showToast(getString(R.string.no_scan_num));
            return;
        }

        MyDialog myDialog = new MyDialog(LoadScanActivity.this);
        myDialog.setIcon(R.drawable.alert);
        myDialog.setMessage("提交后将完成装车，是否提交？");
        myDialog.setPositiveClickListener(Constants.confirmMsg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //查询是否有扫描的单号
                if (!isLoadScan(loadInfos)) {
                    SoundVibratorManager.playSound(2);
                    showToast(getString(R.string.no_scan_num));
                    return;
                }
                //PDA完成装卸车任务
//                completeTask();
                isClickSubmit = true;
                upload(null);
            }
        });
        myDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
        myDialog.show();
    }

    /**
     * PDA完成装卸车任务
     */
    private void completeTask() {
        //检查扫描数据是否都已上传
        final List<UnloadScanTable> list = new ArrayList<>();
        for (CarPlanTaskEntity entity : carPlanTaskEntityList) {
            if (entity.getLoadTasks() != null) {
                for (LoadBillTaskEntity loadTask : entity.getLoadTasks()) {
                    list.addAll(mUnloadScanTableDao.getUnUpload(loadTask.getStowageNo(), operTypeCode));
                }
            }
        }
        if (list == null || list.size() == 0) {
            uploadTask();
            return;
        }
        for (UnloadScanTable item : list) {
            item.setIsUpload(1);
        }
        //实例化上传类
        ScanLoadUploadRequest mScanLoadUploadRequest = new ScanLoadUploadRequest();
        mScanLoadUploadRequest.setRecords(list);
        //关闭扫描
        showPgDlg("正在提交扫描数据...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryUnloadDetailResponse.class)
                .setUrl(Constants.UPLOAD_DATA_POST_URL)
                .setRequestObject(mScanLoadUploadRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast("上传数据失败：" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof QueryUnloadDetailResponse) {
                            //更新数据库状态
                            for (UnloadScanTable item : list) {
                                try {
                                    mUnloadScanTableDao.update(item);
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            }
                            //数据上传后提交任务
                            uploadTask();
                        }
                    }
                });
    }

    private void uploadTask() {
        final List<UnloadScanTable> errorList = LoadUtil.getErrorList(carPlanTaskEntityList, mUnloadScanTableDao, operTypeCode);

        if (!errorList.isEmpty()) {
            //查询是否有异常的运单给出提示

            String errorWaybill = "";
            for (UnloadScanTable scanTable : errorList) {
                errorWaybill += scanTable.getChildWaybillNo() + "\n";
            }

            MyDialog.showAlertDialog(this, "运单上传失败，是否放弃该条码？\n" + errorWaybill, "是", "否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        mUnloadScanTableDao.delete(errorList);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    //设置内存中的数据为未扫描
                    for (UnloadScanTable item : errorList) {
                        //遍历服务器返回数据集合
                        for (LoadInfo billDto : loadInfos) {
                            if (item.getWaybillNo().equals(billDto.getWaybillNo())) {
                                if (billDto.getChildList() != null) {
                                    Iterator<QueryLoadDetailChildBillcode> it = billDto.getChildList().iterator();
                                    while (it.hasNext()) {
                                        QueryLoadDetailChildBillcode child = it.next();
                                        if (child.getChildWaybillNo().equals(item.getChildWaybillNo())) {
                                            it.remove();
                                        }
                                    }
                                    break;
                                }
                                billDto.setWaybillType(1);
                            }
                        }
                    }
                    LoadUtil.setUnloadCount(num, carPlanTaskEntityList, mUnloadScanTableDao, operTypeCode);
                    //根据复选框类型显示运单列表
                    showInfosByCheckBox();
                    SoundVibratorManager.playSound(1);
                }
            }, null);
            return;
        }

        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交装车任务...");

        //扫描数据上传完后  调完成任务
        FinishTaskUploadRequest mFinishTaskUploadRequest = new FinishTaskUploadRequest();
        List<String> list = new ArrayList<>();
        for (CarPlanTaskEntity planTask : carPlanTaskEntityList) {
            if (planTask.getBeTask() == 1) {
                mFinishTaskUploadRequest.setTaskNo(planTask.getTaskNo());
            }
            if (planTask.getLoadTasks() != null) {
                for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                    //添加多个装车配载单
                    list.add(loadTask.getStowageNo());
                }
            }
        }
        mFinishTaskUploadRequest.setStowageNos(list);
        mFinishTaskUploadRequest.setOperTypeCode(operTypeCode);
        mFinishTaskUploadRequest.setOperEmpCode(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryUnloadDetailResponse.class)
                .setUrl(Constants.URL_COMMIT_COMPLETE)
                .setRequestObject(mFinishTaskUploadRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast("提交数据失败：" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof QueryUnloadDetailResponse) {
                            setScannerEnabled(true);
                            dismissPgDlg();

                            Intent unloadScanIntent = new Intent(LoadScanActivity.this, LoadSuccessActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("task", task);
                            bundle.putInt("type", 0);
                            bundle.putString("src", SharedPreferUtil.getInstance().getValue(Common.DEPT_NAME));
                            //小数点后保留3位
                            DecimalFormat df = new java.text.DecimalFormat("#.###");
                            bundle.putString("realWeight", df.format(mRealWeight));
                            bundle.putString("checkWeight", df.format(sfweight));
                            unloadScanIntent.putExtras(bundle);
                            startActivity(unloadScanIntent);
                        }
                    }
                });
    }

    private double getRealWeight() {
        double weight = 0.0;
        for (LoadInfo item : loadInfos) {
            if (item.getScanCount() > 0) {
                weight += BigDecimalUtils.mul(BigDecimalUtils.div(item.getWeight().doubleValue(), item.getSrcPiecesNum(), 4), item.getScanCount());
            }
        }
        return weight;
    }

    @Override
    public void finish() {
        super.finish();
        //退出上传
        isExit = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(CountEvent countEvent) {
        num.setText(countEvent.getCount() + "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(ScanResult scanResult) {
        if (scanResult.getOperSource() == 5 && scanResult.getOperType() == 5) {
            if (UcWaybillValidate.validate(scanResult.getResult())) {
                handleBarCodeResult(scanResult.getResult(), scanResult);
            } else {
                showToast("非快递运单不支持手动添加");
                SoundVibratorManager.playSound(2);
            }
        }
    }
}
